0

我刚刚开始学习 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>

http://jsfiddle.net/zDyn2/18/

谢谢!

4

1 回答 1

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;
};

演示:http: //jsfiddle.net/zDyn2/20/

于 2013-04-12T01:35:19.477 回答