AngularJS:我显然不明白使用ng-init

时间:2016-03-26 00:32:16

标签: javascript angularjs

我的AngularJS控制器中有一个非常分层的JSON结构作为范围变量。我想循环该变量的不同部分。我想过用ng-init来指定我在结构中的位置。这是一些代码:

my_app.js:

(function() {
  var app = angular.module("my_app");
  app.controller("MyController", [ "$scope", function($scope) {
    $scope.things = {
      name: "a",
      children: [
        { 
          name: "a.a",
          children: [
            { name: "a.a.a" },
            { name: "a.a.b" }
          ]
         },
        { 
          name: "a.b",
          children: [
            { name: "a.b.a" },
            { name: "a.b.b" }
          ]
         }
       ]
    }
  }]);
});

my_template.html:

<div ng-app="my_app" ng-controller="MyController">
  <ul>
    <li ng-init="current_thing=things.children[0]" ng-repeat="thing in current_thing.children>
      {{ thing.name }}
    </li>
  </ul>
</div>

我希望这会显示一个列表:

  
      
  • a.a.a
  •   
  • a.a.b
  •   

但它什么都没显示。

当然,如果我明确指定循环(ng-repeat="thing in things.children[0].children"),它就可以正常工作。但是,在我的应用程序的各个层面上,必须在我的应用程序的不同位置运行一小段模板代码。&#34;

(只是为了让生活变得复杂,我可以使用标准JavaScript或者通过Django聪明来获得当前的事物级别。)

有什么想法吗?

1 个答案:

答案 0 :(得分:4)

ng-init的优先级(450)低于ng-repeat(1000)。因此,当放置在同一元素上时,首先编译ng-repeat,这意味着在ng-init执行之后才会定义ng-repeat创建的范围属性。

因此,如果您想以这种方式使用它,则需要将其放在父元素上。

<div ng-app="my_app" ng-controller="MyController">
  <ul ng-init="current_thing=things.children[0]">
    <li ng-repeat="thing in current_thing.children>
      {{ thing.name }}
    </li>
  </ul>
</div>