在AngularJS中的另一个控制器中使用控制器

Evl*_*tnt 8 binding controller angularjs angularjs-controller angularjs-controlleras

为什么我无法绑定到第二个控制器内的控制器变量?

<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"];
}]);
Run Code Online (Sandbox Code Playgroud)

示例:https://jsfiddle.net/nukRe/135/

第二次ng-repeat不起作用.

Pan*_*kar 6

在使用时,controllerAs您应该this在控制器中使用关键字

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

叉小提琴

注意

从技术上讲,你应该一次遵循一种方法.不要将这两种模式混合在一起,使用controllerAs语法/正常控制器声明,就像MainCtrl使用时一样$scope

  • 如果有人偶然发现这个答案,那是正确的,但显然只是从Angular 1.2.1开始.OP小提琴选择了Angular 1.1.1,Pankaj将其设置为1.2.1.花了我15分钟的"为什么这个改变不起作用"才弄明白. (2认同)