将ng repeat中点击的元素的索引从一个页面传递到另一个页面。
将ng repeat中点击的元素的索引从一个页面传递到另一个页面。
我试图通过点击从一个页面传递对象的索引到另一个页面,但是它不起作用。\n需要发送的索引页面如下所示:\n
{{profile.profileName}} | {{profile.created}} | {{$index}} |
\n我的app.js
如下所示:\n
var app=angular.module('message',['restangular','ngRoute']); app.config(['$routeProvider', function ($routeProvider){ $routeProvider .when("/", { templateUrl : "view/Home.html", controller : "MainCtrl" }) .when("/NewUser", { templateUrl : "view/addUser.html", controller : "MainCtrl" }) .when("/ViewUsers", { templateUrl : "view/ViewUsers.html", controller : "MainCtrl" }) .when("/EditUser", { templateUrl : "view/EditUser.html", controller : "MainCtrl" }); }]); app.controller('MainCtrl',function($scope,Restangular,$location){ Restangular.setBaseUrl('webapi'); var profiles = Restangular.all('profiles'); $scope.selected; // This will query /profiles and return a promise. profiles.getList().then(function(profiles) { $scope.profiles = profiles; $scope.saveUser=function(){ $scope.profile.profileName=$scope.profile.firstName+$scope.profile.lastName; console.log($scope.profile); profiles.post($scope.profile); } $scope.showUser=function(id){ console.log(id); $scope.selected=id; $scope.go('/EditUser'); } $scope.editUser=function(id){ console.log(id); var profile=$scope.profiles[id]; console.log(profile); profile.put(); } }); $scope.go = function ( path ) { $location.path( path ); }; });
\n需要传递值的页面如下所示:\n
name: date: {{$scope.id}}
\n有人能给我一些建议吗?
问题的原因:
问题出现的原因是没有在配置中添加":index"。
解决方法:
解决方法是在配置中添加":index"。
为了从一个页面到另一个页面传递被点击的元素的索引,我们可以通过配置路由来接受参数,并使用$routeprovider在URL中添加查询参数。示例如下:
.when("/ViewUsers:index", { templateUrl : "view/ViewUsers.html", controller : "MainCtrl" });
现在,当你想要更改视图时,没有名为$scope.go()的方法,你必须使用$location.path()来导航到视图,并使用.search()方法来添加查询参数。
app.controller('MainCtrl', function ($scope, $location){ $scope.showUser=function(id){ console.log(id); $scope.selected=id; $location.path('/EditUser/').search({index: id}); // this will create the url as **/EditUser/?index=id** } });
在你想要访问索引的其他控制器中,它在$routeparams对象中可用,如下所示:
app.controller('EditCtrl', function ($scope, $routeParams){ var index = $routeParams.index; //This has the value passed from the other controller });
请确保在配置中添加":index"。
问题的原因:
在ng-repeat中点击元素时,想要将点击元素的索引传递给另一个页面。但是该问题出现的原因是在所有的路由中都使用了相同的控制器,这不是一个好的做法。
解决方法:
首先,需要将控制器进行分离,每个路由使用不同的控制器。例如:
.when("/ViewUsers/:id", { templateUrl : "view/ViewUsers.html", controller : "ViewUserCtrl" });
然后,在控制器中获取路由参数的值:
app.controller('ViewUserCtrl', function ($scope, $routeParams){ var id = $routeParams.id; });
为了安全起见,不推荐在路由参数中传递数据。可以使用$rootScope或者服务请求来获取数据。例如,在$rootScope中存储数据并在另一个页面中获取:
app.controller('ViewUserCtrl', function ($scope, $rootScope, $routeParams) { var id = $routeParams.id; $rootScope.profileInfo = //获取相应的数据 });
在另一个页面中可以通过$rootScope来访问profileInfo。
关于Angular的深入学习和安全约束的了解,可以通过查阅相关资料进行学习。