Angular JS observe on directive attribute

谁都会走 提交于 2019-11-29 06:03:06

问题


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


回答1:


From http://docs.angularjs.org/api/ng.$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) {



回答2:


Just watch the value instead of dataValue.

attrs.$observe('value', function (val)  { ...



回答3:


You can also use a new attribute for your directive instead of data-value:

<tile title="Sleep Duration"  your-new-attribute={{sleepHistory.averageSleepTime}}" />

attrs.$observe('yourNewAttribute', function (newValue, oldValue) {
    if (newValue && newValue !== oldValue) {
        // ...
    }
});


来源:https://stackoverflow.com/questions/18748739/angular-js-observe-on-directive-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!