Nicole Stein
Nicole Stein

Reputation: 925

using ng-show in directive template

I am trying to define a directive to show a checkmark when a question has been answered.

questModule.directive('showCheckmarkOnDone', function () {
  return {
    transclude: true,
    template: "<div ng-transclude></div><img src='img/checkmark.svg' " +
        "ng-show='scope.questions[type][number-1].done' " + 
        "class='checkmark' style='height: {{height}}px; width: {{height}}px;'>",
    link: function (scope, element, attrs) {
      scope.height = $(".app").height()/12;
      scope.number = attrs.number;
      scope.type = attrs.type;
    }
  };
});

The scope.questions[type][number-1].done exists in my controller for the page, and I can see that it is being updated correctly when I press the done button. However, the directive does not register the change. I tried putting a $watch in the link function - that didn't help either. I think I'm a bit confused about how to get my directive scope to play nicely with my controller scope - any thoughts on how I can give this directive access to an object that exists in an outside controller? (scope.questions)

Upvotes: 0

Views: 1402

Answers (1)

Langdon
Langdon

Reputation: 20073

This is not a valid way to define directive scope:

scope: '@'

You can either (a) not define it, (b) set it to true, or (c) set it to {} (an object). See the docs for more info: http://docs.angularjs.org/guide/directive (find the header: "Directive Definition Object")

In this case, I imagine if you remove it, you may be OK, because it will allow scope.questions to be visible from your directive. If you reproduce the issue in jsfiddle.net or plnkr.co, it would be much easier to assist you.

Edit:

  1. Your directive generally should have 1 parent element
  2. You should not use scope in your directive's HTML, it's implied
  3. I think you said as much in your comment, but you should strive to make your directive more generic by passing in scope.questions[0][0].done instead of looking it up in your directive's HTML using attributes.

Here's a working example: http://jsfiddle.net/EZy2F/1/

Upvotes: 2

Related Questions