1

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.

Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206

1 Answers1

1

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; 
nipuna-g
  • 6,252
  • 3
  • 31
  • 48
  • But AFAIK `model.selectedItem` is bound to `` and it's passed as a two-way binding property, shouldn't be bar's scope be aware of the whole property changes? – Matías Fidemraizer May 03 '16 at 11:28
  • Your approach worked fine, BTW as I said in my previous comment, I expected that giving a property, either from $scope or from the controller alias should work. – Matías Fidemraizer May 03 '16 at 11:35
  • You define an isolated scope for the directive and it only contains `scope: { items: "=" }`, I believe that the directive only has access to that specific object. – nipuna-g May 03 '16 at 11:42
  • It's strange, but we can't change Angular behavior ;P – Matías Fidemraizer May 03 '16 at 12:13