Angular指令解析的attr双向绑定

Angular Directive parsed attr two-way binding

我正在创建一个名为 evoEventMirror 的 angular 指令,其目的是将 jquery 事件附加到插入的元素并将指定的 css 样式应用于 "root"元素。 请参阅下面的示例:

<div id="#mydiv" evo-event-mirror target="#otherdiv" event="transitionEnd" action="hideMenu == true ? {'border':'1px solid blue'} : {'border':'1px solid red'}">
       <!--...-->
</div>

在这种情况下,#otherdiv 将绑定 transitionEnd 事件,并在事件触发时将边框样式(动作)应用到 #mydiv。

现在,问题是我无法创建独立作用域,因此无法获取双重绑定变量。 我尝试使用元素的属性作为输入源,但如果变量 "hidemenu" 发生变化,我无法拦截任何变化。

evoDirectives.directive('evoEventMirror', ['$parse',function ($parse) { 
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {

            var test = $parse(attrs.action)(scope);
            scope.$watch(test, function (newValue) {
                console.log('update');
            });             

           //apply some style..
            target.bind('transitionend webkitTransitionEnd oTransitionEnd otransitionend', function () {
                var css = angular.element(element).attr('style');
                if (css == null) css = style;
                else css += style;

                element.attr('style', css);
            });
        }
    }
}]);

不确定,但我相信 watch 在这里用处不大,因为 test 不是范围变量。

你可以做的是像这样创建一个监视函数:

            var getter = $parse(attrs.action);
            scope.$watch(function() {
                             return getter(scope);
                         }, 
                        function (newValue) {
                                 console.log('update');
                        });    

这个监视函数(第一个参数)现在每次在摘要循环时都会触发。试试吧。

你需要在指令上隔离作用域,像这样(未测试):

.directive('evoEventMirror', function ($parse) {
    return {
        restrict: 'A',
        scope: {
            'action': '='
        },
        link: function (scope, element, attrs) {
            console.log(scope.action);            
        }
    }
});

您可以阅读的一个很好的指南是 here

我成功解决了我的问题。 问题是 "hidemenu" 变量本身:它存储在一个独立的范围内,所以我引用了一个 "new" 变量 hidemenu,它每次都是假的。

然而,使用一个普通的 watcher 来监视 attrs 就可以了。

无论如何,感谢您的回答。