问题很简单,我在控制器中有价值,我想将此值发送给另一个控制器。
我有这段代码:
var app = angular.module("MyApp", []);
app.factory("UserService", function() {
var users = //how to get the value user of MyCtrl ?
return {
all: function() {
return users;
},
first: function() {
return users[0];
}
};
});
app.controller("MyCtrl", function($scope, UserService) {
var users = ["Peter", "Daniel", "Nina"];
$scope.users = UserService.all();
});
app.controller("AnotherCtrl", function($scope, UserService) {
$scope.firstUser = UserService.first();
});
我不知道如何从var users = ["Peter", "Daniel", "Nina"];
中的控制器MyCtrl
获取UserService
的值?
答案 0 :(得分:0)
您可以将其注入您的函数:
app.factory('UserService', ['MyCtrl', function(MyCtrl) {
var users = MyCtrl.users;
...
};
app.controller("MyCtrl", function($scope, UserService) {
var users = ["Peter", "Daniel", "Nina"];
$scope.users = UserService.all();
return {
users: users
};
});