trubliphone
trubliphone

Reputation: 4504

AngularJS: I clearly do not understand the use of ng-init

I have an extremely hierarchical JSON structure as a scope variable in my AngularJS controller. I want to loop around different sections of that variable. I thought about using ng-init to specify where in the structure I am. Here is some code:

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>

I would expect this to display a list:

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

But it displays nothing.

Of course, if I specify the loop explicitly (ng-repeat="thing in things.children[0].children") it works just fine. But that little snippet of template code will have to be run at various points in my application at various levels of "things."

(Just to make life complicated, I can get the current thing level using standard JavaScript or else via Django cleverness.)

Any ideas?

Upvotes: 2

Views: 132

Answers (1)

David L
David L

Reputation: 33833

ng-init runs at a lower priority (450) than ng-repeat (1000). As a result, when placed on the same element, ng-repeat is compiled first meaning that the scope property created by ng-init won't be defined until after ng-repeat is executed.

As a result, if you want to use it in this manner, you'd need to place it on the parent element instead.

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

Upvotes: 4

Related Questions