Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular JS observe on directive attribute

How can angular js watch attributes on custom directive in order to accept angular values to be bind

Here is what I have so far:

<tile title="Sleep Duration" data-value="{{sleepHistory.averageSleepTime}}"/>

app.directive('tile', [function() {
    return {
        restrict: 'E',
        link: function(scope, element, attrs) {
            var title = attrs.title;

            attrs.$observe('dataValue', function(val) {
                var data = val;

                console.log(data);

                var dom =
                    "<div>" +
                    "<p>" + title + "</p>" +
                    "<p>" + data + "</p>" +
                    "</div";

                $(element).append($(dom.trim()));
            });
        }
    };
}]);

but the observed value is coming back as undefined

like image 350
Horace Heaven Avatar asked Sep 11 '13 18:09

Horace Heaven


2 Answers

From https://docs.angularjs.org/api/ng/type/$compile.directive.Attributes:

all of these are treated as equivalent in Angular:

<span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">

So the attribute data-value normalizes to value

So, this is what you want:

attrs.$observe('value', function(val) {
like image 91
dnc253 Avatar answered Nov 17 '22 07:11

dnc253


Just watch the value instead of dataValue.

attrs.$observe('value', function (val)  { ...
like image 31
zs2020 Avatar answered Nov 17 '22 07:11

zs2020