hud
hud

Reputation: 203

Angular.JS directive not updating

I am updating a scope array called $scope.arrangement using a click function, but this is not causing my directive to update and update the DOM.

/******************************************
  Sort function
******************************************/  

  $scope.sort = function() {
        $scope.arrangement.sort(function(a, b){
            var keyA = a.created,
        keyB = b.created
        // Compare the 2 dates
        if(keyA < keyB) return -1;
        if(keyA > keyB) return 1;
        return 0;
        })
        for (b=0;b<$scope.arrangement.length;b++) { 
            if($scope.arrangement[b].ord !== b) {
                console.log('order was '+$scope.arrangement[b].ord + " now " + b)
                $scope.arrangement[b].ord=b;
            }
        }
    }
})

/******************************************
  Directives
******************************************/

app.directive('item', function() {
  return {
    restrict: 'A',
    scope: {
      count: "=",
      arrangement: "="
    },
    link: function(scope,element,attrs) {
      console.log('updated')
      for (a=0;a<scope.arrangement.length;a++) {
        if (scope.arrangement[a].ord === scope.count) {
          element.html("Item "+scope.arrangement[a].id + " Created: " + scope.arrangement[a].created)
        }
      }
    }
  }
})

Here's a plunker: http://plnkr.co/edit/hT0HQ85yaPkQj2JcASrY

By clicking 'sort', I am expecting the $scope.sort function to run and this in turn to refresh my directive. What actually happens is the $scope.sort function runs but the directive does not update.

Note that I deliberately not using an ng-repeat here.

Upvotes: 0

Views: 73

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191819

The link function only runs one time. elem.html does not use data bindings, so this will just set up the HTML of the element initially when the directive is linked. You can set up a watch yourself:

scope.$watchCollection('arrangement', function () {
  for (a=0;a<scope.arrangement.length;a++) {
    if (scope.arrangement[a].ord === scope.count) {
      element.html("Item "+scope.arrangement[a].id + " Created: " + scope.arrangement[a].created)
    }
  }
});

Seems like it would be much easier to use built in directives, though:

<span ng-if="arr.ord == s.count" ng-repeat="arr in arrangement">
  Item {{arr.id}} Created: {{arr.created}}
</span>

Upvotes: 2

Related Questions