【问题标题】:How to access main controller variable in Router UI controller in AngularJS?如何在AngularJS的Router UI控制器中访问主控制器变量?
【发布时间】:2015-02-24 00:57:35
【问题描述】:

我正在尝试使用 AngularJS 创建一个 CRUD 页面,我使用 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('/');

$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');
            };
        }
    });

});

【问题讨论】:

  • 如果您将editadd 设为list 的子路由,那么您只需将persons 设为解析即可。然后所有子路由都可以注入它。

标签: javascript angularjs controller angular-ui-router


【解决方案1】:

与其在 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;
});

【讨论】:

    猜你喜欢
    • 2023-03-10
    • 2017-09-22
    • 2016-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    • 2013-10-08
    相关资源
    最近更新 更多