axelvnk
axelvnk

Reputation: 442

Watcher on a element attribute to change the elements inner html

The div's content is being filled up with the content of the attribute sk-placeholder. I have an if statement which will fill up the content of the div with a certain text or an empty string depending on the boolean viewer.building.

<div contentEditable="[[viewer.building]]" class="course-description"
ng-model="viewer.course.description" sk-replace
sk-placeholder="[[viewer.building && 'Summarise the content of your course
by  writing a short blurb. You can add a more elaborate description on
the next  page.' || '']]"></div>

When the placeholders content changes, an event needs to be fired, to empty the content of the div. I made a new directive called sk-replace that should do that. But the event is not firing.

SEK.app.directive("skReplace", function ()
{
    return {
        restrict:'AEC',
        link: function(scope, elem, attrs) {
             scope.$watch(attrs.skPlaceholder.value, function(v) {
                v = attrs.skPlaceholder;
                if(v.length < 1){
                    elem.html('');
                };
            });
        }
    }
});

The function is executed on page load. But not when the placeholder's content changed. (this is done by a button btw)

Any help?

Upvotes: 0

Views: 833

Answers (2)

Tom A
Tom A

Reputation: 964

$watch takes either a function or a string as the first parameter, so you have two options (three if you use observe instead). Option one (bind to scope):

scope.val = attrs.skPalceholder.value;    
scope.$watch('val', function(v) {
  if(v.length < 1) {
    elem.html('');
  };
});

Option two (return value from function)

scope.$watch(function() {
  return attrs.skPlaceholder.value;
}, function(v) { 
  if(v.length < 1){
    elem.html('');
  };
});

Edit - I see observe was covered in another answer, and might be more elegant than the watcher solutions. Up to you.

Upvotes: 1

Preview
Preview

Reputation: 35806

You should use $observe instead :

attrs.$observe('skPlaceholder', function (value) {
  if (value.length < 1) {
    elem.html('');
  };
});

Upvotes: 3

Related Questions