【问题标题】:Using controller inside another controller in AngularJS在 AngularJS 的另一个控制器中使用控制器
【发布时间】:2015-08-18 01:33:33
【问题描述】:

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

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

【问题讨论】:

    标签: angularjs binding controller angularjs-controller angularjs-controlleras


    【解决方案1】:

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

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

    Forked Fiddle

    注意

    从技术上讲,您应该一次采用一种方法。不要混淆 这两种模式一起,要么使用controllerAs语法/正常 控制器声明,就像你为 MainCtrl 使用 $scope 所做的那样

    【讨论】:

    • 如果有人偶然发现这个答案,它是正确的,但显然只从 Angular 1.2.1 开始。 OP fiddle 选择了 Angular 1.1.1,Pankaj 将其设置为 1.2.1。我花了 15 分钟“为什么这个改变不起作用”来弄清楚。
    【解决方案2】:

    删除

    在里面

    从这里开始:

    &lt;div ng-controller="InsideCtrl as inside"&gt; 这样:

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

      【讨论】:

      • 欢迎来到 Stack Overflow!请解释为什么这行得通,现在它是一个不合标准的答案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多