如何在AngularJS中的Router UI控制器中访问主控制器变量?

时间:2014-12-26 20:43:17

标签: javascript angularjs controller angular-ui-router

我正在尝试创建一个CRUD页面,使用AngularJS,我使用Angular Router UI进行页面更改

如何在Controller路径的主controller中访问变量?

//This is my main controller:
var app = angular.module('app', [
    'ui.router'
]);
app.controller('MyCtrl', function ($scope) {
    $scope.persons = [
        {name: 'Daisy', description: 'Developer'},
        {name: 'Zelda', description: 'Developer'},
        {name: 'Luide', description: 'Developer'},
        {name: 'Mario', description: 'Developer'}
    ];
});

这是我的路由器配置 app.config(function($ stateProvider,$ urlRouterProvider){     $ urlRouterProvider.otherwise(' /&#39);

$stateProvider
    .state('list', {
        url: '/list',
        templateUrl: 'list.html',
        controller: 'MyCtrl'
    })
    .state('edit', {
        url: '/edit',
        templateUrl: 'edit.html',
        controller: function($scope, $state) {
            $scope.person = {name: "", description: ""};

            $scope.click = function () {
                $state.go('list');
            };
        }
    })
    .state('add', {
        url: '/add',
        templateUrl: 'edit.html',
        controller: function($scope, $state) {
            $scope.person = {name: "", description: ""};

            $scope.click = function () {
                // HOW TO CAN I ACCESS $SCOPE.PERSONS FOR MAKE THIS PUSH?
                $scope.persons.push($scope.person);
                $state.go('list');
            };
        }
    });

});

1 个答案:

答案 0 :(得分:4)

不是在MainController中创建$ scope.persons,而是使用服务存储person对象可能更好:

app.service("People", function () {
   this.persons = [
        {name: 'Daisy', description: 'Developer'},
        {name: 'Zelda', description: 'Developer'},
        {name: 'Luide', description: 'Developer'},
        {name: 'Mario', description: 'Developer'}
    ];
});

然后你可以将它注入你的控制器(上面的代码):

.state('add', {
        url: '/add',
        templateUrl: 'edit.html',
        controller: function($scope, $state, People) {
            $scope.person = {name: "", description: ""};

            $scope.click = function () {
                //use persons object of people service.
                People.persons.push($scope.person);
                $state.go('list');
            };
        }
    });

});

您可以通过依赖注入在不同的控制器,服务和指令之间共享这些人员。例如,您的列表控制器(MyCtrl)将如下所示:

app.controller('MyCtrl', function ($scope, People) {
    $scope.persons = People.persons;
});