Using controller inside another controller in AngularJS

[亡魂溺海] 提交于 2019-12-04 20:06:18

问题


Why I can't bind to controller's variable inside second controller?

<div ng-app="ManagerApp">
    <div ng-controller="MainCtrl">
        Main: 
        <div ng-repeat="state in states">
            {{state}}
        </div>
        <div ng-controller="InsideCtrl as inside">
            Inside:
            <div ng-repeat="state in inside.states2">
                {{state}}
            </div>
        </div>
    </div>
</div>

var angularApp = angular.module('ManagerApp', []);

angularApp.controller('MainCtrl', ['$scope', function ($scope) {
    $scope.states = ["NY", "CA", "WA"];
}]);

angularApp.controller('InsideCtrl', ['$scope', function ($scope) {
    $scope.states2 = ["NY", "CA", "WA"];
}]);

Example: https://jsfiddle.net/nukRe/135/

Second ng-repeat doesn't work.


回答1:


As you are using controllerAs you should be using this keyword in controller

angularApp.controller('InsideCtrl', [ function() {
    var vm = this;
    vm.states2 = ["NY", "CA", "WA"];
}]);

Forked Fiddle

NOTE

Technically you should follow one approach at a time. Don't mix up this two pattern together, Either use controllerAs syntax/ Normal controller declaration as you did for MainCtrl using $scope




回答2:


Remove

as inside

from here:

<div ng-controller="InsideCtrl as inside"> such that:

`<div ng-controller="InsideCtrl">`



回答3:


<div ng-app="ManagerApp">
    <div ng-controller="MainCtrl">
        Main: 
        <div ng-repeat="state in states">
            {{state}}
        </div>
        <div ng-controller="InsideCtrl">
            Inside:
            <div ng-repeat="state in states2">
                {{state}}
            </div>
        </div>
    </div>
</div>


来源:https://stackoverflow.com/questions/30626903/using-controller-inside-another-controller-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!