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

时间:2015-06-03 17:31:36

标签: angularjs binding controller 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"];
}]);

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

第二次ng-repeat不起作用。

3 个答案:

答案 0 :(得分:6)

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

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

Forked Fiddle

注意

  

从技术上讲,您应该一次遵循一种方法。别搞砸了   这两个模式在一起,要么使用controllerAs语法/正常   您使用MainCtrl

$scope所做的控制器声明

答案 1 :(得分:0)

删除

  

在里面

从这里开始:

<div ng-controller="InsideCtrl as inside"> 这样:

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

答案 2 :(得分:-2)

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