10

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

<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 不起作用。

4

3 回答 3

8

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

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

分叉的小提琴

笔记

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

于 2015-06-03T17:34:57.693 回答
0

消除

作为里面

从这里:

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

`<div ng-controller="InsideCtrl">`
于 2017-07-21T14:27:48.880 回答
-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>
于 2017-09-11T08:21:37.947 回答