60

是否可以“监视”指令上的 ui 更改?类似的东西:

.directive('vValidation', function() {
    return function(scope, element, attrs) {
        element.$watch(function() {
            if (this.hasClass('someClass')) console.log('someClass added');
        });
    }
})
4

3 回答 3

93

是的。attr.$observe如果在属性处使用插值,则可以使用。

但是,如果这不是一个插值属性,并且您希望它从应用程序的其他地方更改(极不推荐,请阅读Common Pitfalls),那么您可以$watch返回一个函数:

scope.$watch(function() {
    return element.attr('class'); 
}, function(newValue){
    // do stuff with newValue
});

无论如何,对您来说最好的方法可能是更改更改元素类的代码。哪个瞬间变了?

于 2013-04-09T20:10:13.817 回答
40
attrs.$observe('class', function(val){});
于 2013-04-09T19:59:31.933 回答
2

您还可以在控制器中观察变量。

此代码在其他模块显示反馈消息后自动隐藏通知栏。

HTML:

<notification-bar
    data-showbar='vm.notification.show'>
        <p> {{ vm.notification.message }} </p>
</notification-bar>

指示:

var directive = {
    restrict: 'E',
    replace: true,
    transclude: true,
    scope: {
        showbar: '=showbar',
    },
    templateUrl: '/app/views/partials/notification.html',
    controller: function ($scope, $element, $attrs) {

        $scope.$watch('showbar', function (newValue, oldValue) {
            //console.log('showbar changed:', newValue);
            hide_element();
        }, true);

        function hide_element() {
            $timeout(function () {
                $scope.showbar = false;
            }, 3000);
        }
    }
};

指令模板:

<div class="notification-bar" data-ng-show="showbar"><div>
    <div class="menucloud-notification-content"></div>
于 2016-09-15T11:34:53.527 回答