2015-10-14 28 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

仍然不是加工 –

相关问题