Controller property change doesn't affect the whole bound property on some directive

89 Views Asked by At

Let's say I've implemented a directive as follows:

module.directive("foo", function($scope) {
      return {
          controllerAs: "model",
          controller: function($scope) {
              this.items = $scope.items;

              this.selectItem = function(item) {
                   this.selectedItem = item;
              };
          },
          scope: { items: "=" }
      };
});

module.directive("bar", function($scope) {
      return {
          controllerAs: "model",
          controller: function() { 
               this.item = $scope.item;
          },
          scope: { item: "=" }
      };
});

...where foo directive's template would look as follows:

<bar item="model.selectedItem" />
<ol>
<li ng-repeat="item in model.items" ng-click="model.selectItem(item)">
    <bar item="item" />
</li>
</ol>

...and bar directive's template would look as:

<span ng-bind="item.text"></span>

TL;DR: My issue

When model.selectedItem changes because user has clicked on some repeated <bar />, the outer <bar /> is unaware of any the so-called property change. That is, the outer <bar /> won't update its bound model.text property.

I can't figure out why a model change on foo's controller won't change the outer bar directive.

1

There are 1 best solutions below

4
nipuna-g On BEST ANSWER

selectedItem lives in the foo directives scope. Therfor, it won't be visible to the outside(the bar directive).

You could keep another variable containing the key of the selected item. Then in the bar directive you can bind the value as follows,

<bar item ="items[selectedKey].text"></bar>

edit: You could also try, setting the value on the scope rather than on this.

$scope.selectedItem = item;

Instead of

this.selectedItem = item;