如何为应用程序中的每个控制器实例使用不同的初始化变量集?
视图中:
<div ng-controller="showProjectList">
{{project_list}}<!--user 1-->
</div>
<div ng-controller="showProjectList">
{{project_list}}<!--user 2-->
</div>在控制器中
myapp.controller('showProjectList',function($http)
{ $scope.project_list= <Here I have a http request with argument user_id to fetch project_list>
}现在如何用不同的user_id初始化每个控制器?我在stackexchange和google-groups上读到的一种解决方案是使用ng-init.(link google-grp:https://groups.google.com/forum/#!topic/angular/J6DE8evSOBg) .However在相同的线程中注意不要使用ng-init。那么,如何使用数据初始化控制器呢?
发布于 2014-05-29 09:21:32
在这方面,您可以使用控制器、指令和服务的组合。
控制器持有用户的id。
该指令正在呈现项目列表。
该服务负责从服务器获取数据。您可以在此处实现缓存和/或使用$resource。
以下是模板代码:
<div ng-controller="Projects">
<!-- here you can put an input element with
ng-model="users" to modify the user list on the fly -->
<div ng-repeat="user in users">
<project-list user="user" />
</div>
</div>控制器:
myapp.controller('Projects', ['$scope', function($scope) {
$scope.users = [1, 2, 3];
}]);指令:
myapp.directive('projectList', ['UserService', function(UserService) {
return {
restrict: 'E',
scope: {
user: "="
},
templateUrl: 'project-list.html',
link: function($scope, $element, $attrs) {
UserService.getUserProject($scope.user).then(function(response) {
$scope.userProjects = response;
});
}
};
}]);服务:
myapp.factory('UserService', ['$http', function($http) {
var getUserProject = function(user) {
var promise = $http.get('users/' + user + '/project');
return promise;
}
return {
getUserProject: getUserProject
}
}]);https://stackoverflow.com/questions/23924175
复制相似问题