Michael
Michael

Reputation: 16122

Can't access scope from the directive template

Directive:

angular.module('myApp')
  .directive('rankingTags', function() {
    return {
      restrict: 'E',
      scope: {},
      controller: function($scope) {
        $scope.updateTagList = function(tag) {
          console.log('updateTagList function called') // never logged
        };
      },

      templateUrl: '/app/common/directives/tags.tpl.html',
      replace: true
    };
  });

Template for the directive:

<div class="tag" ng-repeat="tag in $root.collection.tags track by $index">
  <input ng-click="updateTagList(tag)" type="checkbox" />
  <label>{{tag.name}}</label>
</div>

Calling directive from another template:

<ranking-tags></ranking-tags>

I can't access updateTagList function from the directive template. So somehow this controller isn't linked to the template.

What am I doing wrong?

Upvotes: 4

Views: 729

Answers (2)

ajmajmajma
ajmajmajma

Reputation: 14216

You do not need replace: true (this is what is breaking your function), instead you can use transclude:true if you like. Replace is depricated.

from the change -

The replace flag for defining directives that replace the element that they are on will be removed in the next major angular version. This feature has difficult semantics (e.g. how attributes are merged) and leads to more problems compared to what it solves. Also, with WebComponents it is normal to have custom elements in the DOM.

AFAIK it is not removed but the known bugs are not fixed, you can check out the thread here if you are interested further. https://github.com/angular/angular.js/commit/eec6394a342fb92fba5270eee11c83f1d895e9fb#commitcomment-8124407

Upvotes: 3

Joseph
Joseph

Reputation: 119827

$root.collection.tags should simply be just tags since the scope of the template is already the $scope of the directive.

Upvotes: 0

Related Questions