Stephen Thomas
Stephen Thomas

Reputation: 14053

Recursive Components in AngularJS 1.x

Finally trying to learn AngularJS and I can't quite figure out how to make components work recursively. I have a simple example that's not rendering as expected.

HTML

<body ng-app="myApp" ng-controller="myCtrl as vm">
  <nested-list list="vm.list"></nested-list>
</body>

JavaScript

angular.module('myApp', [])

  .controller('myCtrl', ['$scope', function($scope) {
    $scope.list = [
      { "name": "Item 1" }, 
      { "name": "Item 2",
        "subItems": [
          { "name": " Item 2.1" }
        ]
      }, 
      { "name": "Item 3",
        "subItems": [
          { "name": " Item 3.1" }, 
          { "name": "Item 3.2",
            "subItems": [
              { "name": "Item 3.2.1" },
              { "name": "Item 3.2.2" }
            ]
          }
        ]
    }];
  }])

  .component('nestedList', {
    bindings: {
      list: '<'
    },
    template: `
      <div ng-repeat="item in $ctrl.list" >
        <div> {{item.name}} </div>
        <nested-list list="item.subItems"></nested-list>
      </div>
    `
  });

Undoubtedly because I'm missing something obvious, the list from the app's main controller myCtrl isn't getting bound to the root component. If anyone can provide insight, I'd be grateful.

Stephen

Upvotes: 2

Views: 457

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

As you are using controllerAs, you should be binding values to controller this(context) instead of binding values to $scope.

.controller('myCtrl', [function() {
    var vm = this;
    vm.list = [ ..];
}]);

Plunker Here

Upvotes: 3

Related Questions