2015-10-14 62 views
0

我正在學習Angular JS我正在製作一個簡單的應用程序,該應用程序應該以人員列表開始,當用戶單擊「更新用戶」時應該重定向到一個編輯頁面,數據應該被填充,這不會發生。這裏是我的代碼:當跳轉到另一個視圖時,值不會被填充

起始頁面的HTML:

var app = angular.module('app', ['ngRoute']); 
 

 
app.config(['$routeProvider', function ($routeProvider, $locationProvider) { 
 

 
    $routeProvider 
 
     .when('/listview', 
 
      { 
 
       controller: 'SimpleController', 
 
       templateUrl: 'Partials/ListView.html' 
 
      }) 
 
     .when('/tableview', 
 
      { 
 
       controller: 'SimpleController', 
 
       templateUrl: 'Partials/TableView.html' 
 
      }) 
 
     .when('/edit/:id', 
 
      { 
 
       controller: 'EditCtrl', 
 
       templateUrl: 'Partials/Edit.html' 
 
      }) 
 
     .otherwise({ redirectTo: '/listview' }); 
 
}]); 
 

 
app.controller('EditCtrl', function ($scope, $location, $routeParams) { 
 
    $scope.details = $scope.persons[$routeParams.id]; 
 

 
    $scope.save = function() { 
 
     $location.path('/'); 
 
    }; 
 
}); 
 

 
app.controller('SimpleController', function ($scope) { 
 
    $scope.persons = [{ name: 'Tiago', city: 'Lisbon', age: 26 }, 
 
         { name: 'Ecem', city: 'Antalya', age: 24 }, 
 
         { name: 'Derya', city: 'Istambul', age: 24 } 
 
    ]; 
 
});
<!DOCTYPE html> 
 
<html xmlns="http://www.w3.org/1999/xhtml"> 
 
<head> 
 
    <title>Galaksiyia - TableView</title> 
 
</head> 
 
<body> 
 
    <table style="width:100%"> 
 
     <tr> 
 
      <th>Index</th> 
 
      <th>Name</th> 
 
      <th>City</th> 
 
      <th>Age</th> 
 
      <th></th> 
 
     </tr> 
 
     <tr ng-repeat="details in persons"> 
 
      <td>{{$index}}</td> 
 
      <td>{{details.name}}</td> 
 
      <td>{{details.city}}</td> 
 
      <td>{{details.age}}</td> 
 
      <td><a href="#/edit/{{$index}}">Update User</a></td> 
 
     </tr> 
 
    </table> 
 
</body> 
 
</html>

並在編輯頁面的HTML是:

<!DOCTYPE html> 
 
<html xmlns="http://www.w3.org/1999/xhtml"> 
 
<head> 
 
    <title>Galaksiyia - Edit Page</title> 
 
</head> 
 
<body> 
 
    <form> 
 
     <input type="text" ng-model="details.name" placeholder="Name" /><br /> 
 
     <input type="text" ng-model="details.city" placeholder="City" /><br /> 
 
     <input type="text" ng-model="details.age" placeholder="Age" /><br /> 
 
     <button ng-click="save()">Update User</button> 
 
    </form> 
 
</body> 
 
</html>

此外,單擊保存按鈕時什麼也沒有發生,並且根據代碼,用戶應該被重定向到主頁面。

+0

你能否轉到下一頁? – ngLover

+0

這些對象的範圍僅在它僅使用的控制器中。在其他控制器中,它將是未定義的。 –

+0

@ngLover你是什麼意思?從表頁傳遞到編輯頁面?是的,索引正確傳遞 –

回答

0

迅速解決您的proplem是把數據(即必須在兩個控制器提供)到$ rootScope

app.controller('SimpleController', function ($scope) { 
    $rootScope.persons = [{ name: 'Tiago', city: 'Lisbon', age: 26 }, 
         { name: 'Ecem', city: 'Antalya', age: 24 }, 
         { name: 'Derya', city: 'Istambul', age: 24 } 
    ]; 
}); 

更好的解決辦法是寫一個服務(廠),並獲得來自該服務的數據。

+0

它不工作! –

+0

請務必更改此代碼:'$ scope.details = $ scope.persons [$ routeParams.id];' - > $ scope.details = $ rootScope.persons [$ routeParams.id];' –

+0

仍然不是加工 –