2016-04-30 74 views
1

我試圖製作一個網頁。當用戶登錄時,在視圖中打開一個新的html頁面(「dashboard.html」)。這個「dashboard.html」包含一些鏈接(指向其他html頁面的鏈接)。當用戶點擊它們時,一個新的html頁面(比如說「page_3.html」)應該打開,其中包含controller.this中的數據「page_3.html」沒有從控制器中獲取數據。下面是我的代碼。無法從angularjs中的多個html頁面中的控制器獲取數據

<!-- controller.js --> 
 
    var app = angular.module('myApp',[ 'ngRoute' ]); 
 
    app.config(function($routeProvider){ 
 
     $routeProvider 
 
     .when('/',{ 
 
      templateUrl: 'login.html' 
 
     }) 
 
     .when('/dashboard',{ 
 
      templateUrl: 'dashboard.html' 
 
    }) 
 
     .when('/page_3',{ 
 
      templateUrl: 'page_3.html' 
 
     }) 
 
     .otherwise({ 
 
      redirectTo : '/' 
 
     }); 
 
     
 
    }); 
 

 

 
    app.controller('app', function($scope, $location){ 
 
    $scope.item = "test"; 
 
     $scope.submit = function(){ 
 
       $location.path('/dashboard'); 
 
      } 
 
     }; 
 
    });
<!DOCTYPE html> 
 
    <html> 
 
     <head> 
 
      <title>Project</title> 
 
      <script src="angular.js"></script> 
 
      <script src="angular-route.js"></script> 
 
      <script src="controller.js"></script> 
 
     </head> 
 
     <body ng-app= "myApp" ng-controller="app"> 
 
      <div ng-view></div> 
 
     </body> 
 
    </html> 
 

 
    <!-- below is login.html page --> 
 

 
    <div ng-controller="app">  
 
    <form action="/"> 
 
     <button type="button" ng-click="submit()">Login</button> 
 
      </form> 
 
    </div> 
 

 
    <!-- below is my dashboard.html page --> 
 
    <div ng-controller="app"> 
 
     <h1>Page_3</h1> 
 
      <div><a href='page_3.html'>page_3</a></div> 
 
     </div> 
 
     
 
     <!-- below is page_3.html page --> 
 

 
    <div ng-controller="app"> 
 
    <p>{{item}}</p> 
 
    </div>

結果:{{項目}}

+0

您能否創建我們可以使用的[最小,完整和可驗證示例](https://stackoverflow.com/help/mcve)? –

回答

0

我可以建議避免ng-controller指令和而使用controller配置對象在路由器上?

.when('/page_3',{ 
    templateUrl: 'page_3.html', 
    controller: "app" 
}) 
+0

我試過了。它不工作。 – VivekT

0

有你的代碼的兩個主要問題:

  1. 啓用HTML 5模式pushState via $locationProvider針對URL像/dashboard/page_3
  2. 解決了在路由配置爲/page_3這個問題,但有a標記指向/page_3.html

要工作例如:

  • 添加鹼標籤

    <base href="/"> 
    
  • config塊經由locationProvider啓用HTML5模式中dashboard.html

    $locationProvider.html5Mode(true); 
    
  • 修正路線

    <!-- below is dashboard.html page --> 
    <div ng-controller="app"> 
        <h1>Page_3</h1> 
         <div><a href='page_3.html'>page_3</a></div> 
        </div> 
    

Click here for the demo/jsbin.

其他/建議:作爲Zack Briggs建議;在路由中使用控制器語法將有助於您在路由器配置中找到更好的代碼結構/設計,directivescomponents。把所有東西放在一個地方對於一個正在成長的項目來說通常是一個壞主意

相關問題