我刚开始学习Angular.js。我正在尝试从CtrlA调用函数到CtrlB。我该怎么做?
这是我到目前为止所拥有的 -
var app = angular.module('myApp', []);
function UserCtrl($scope) {
$scope.users = [
{id: 1, name: 'Mike Smith'},
{id: 2, name: 'Jane Doe'}
];
$scope.getDetails = function(userId) {
//Call getUserById in UserDetailCtrl. How?
};
};
function UserDetailCtrl($scope) {
$scope.getUserById = function(userId) {
alert('test');
};
};
查看 -
<div ng-controller="UserCtrl">
<ul>
<li ng-repeat="user in users">
<a ng-click="getDetails(user.id)">{{user.name}}</a>
</li>
</ul>
</div>
谢谢!
答案 0 :(得分:3)
要在控制器和指令之间共享数据和/或方法,请使用服务并在需要时注入该服务:
var app = angular.module('myApp', []);
app.factory('MyDataService', function () {
var Users = {
activeUser: {},
users: [{ id: 1,name: 'Mike Smith'},
{ id: 2,name: 'Jane Doe'}],
setActiveUserName:function( name){
Users.activeUser.name=name;
}
}
return Users
})
function UserCtrl($scope, MyDataService) {
$scope.users = MyDataService.users;
$scope.setActiveUserName = function (user) {
MyDataService.setActiveUserName( user.name);
}
};
function UserDetailCtrl($scope, MyDataService) {
$scope.activeUser = MyDataService.activeUser;
};