Angular $watch 不会在我的指令中触发任何事件 [英] Angular $watch does not fire any event in my directive

查看:22
本文介绍了Angular $watch 不会在我的指令中触发任何事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试根据自定义指令的属性值更新元素内容.下面的代码运行良好,但仅在站点加载时执行一次.属性值的动态更新不会触发任何事件.我做错了什么?

i try to update an elements content depending on the attribute value of my custom directive. the code below performs well but only once on site-load. dynamic updates on the attribute value do not fire any event. what do i do wrong?

ng-repeat 中的标记(匹配匹配):

markup inside ng-repeat (match in matches):

<div ng-tipp-result="[[getIconClass(match)]]"></div>

指令:

myApp.directive('ngTippResult', function() {
    return {
        restrict: 'A',
        link: function(scope, elem, attrs) {
            var content = "s";

            scope.$watch(attrs.ngTippResult, function(v){
                switch(v){
                    case 1: content = '<i class="icon-circle"></i>';break;
                    case 2: content = '<i class="icon-X"></i>';break;
                    case 3: content = '<i class="icon-Y"></i>';break;
                    case 4: content = '<i class="icon-Z"></i>';break;
                    case 5: content = '<i class="icon-ok"></i>';break;
                    case 6: content = '<i class="icon-minus"></i>';break;
                }

                elem.html(content);
            });
        }
    };
});

使用属性名称作为字符串解决了这个问题,但导致了另一个问题,我遇到了上面代码的无限摘要循环.

using the attributes name as string solved the problem but caused another, i ran into a infinit digest loop with the code above.

<li ng-repeat="match in matches">
    <i class="pull-right [[getIconClass(match)]]"></i>
</li>

getIconClass 是一个控制器方法,它根据匹配返回从 1 到 6 的值.

getIconClass is a controller method which returns values from 1 to 6 depending on match.

推荐答案

$watch 的第一个参数应该是你想要观察的值的 getter 函数.试试

The first parameter to $watch should be a getter function for the value you want to watch. Try

scope.$watch(function(){return attrs.ngTippResult}, function(v){...});

此处查看文档.

可能发生的事情是 attrs.ngTippResult 正在评估一个字符串.String 是一个有效的输入,但我认为这不是您想要的;每次 attrs.ngTippResult 更改时,您似乎都希望更新.相反,您当前的代码正在使用 attrs.ngTippResult 的值监视范围上的属性(例如,如果 attrs.ngTippResult 是 "fish",则您将使用当前代码监视的值实际上是 $scope.fish,这可能不是您想要的.

What's probably happening is that attrs.ngTippResult is evaluating to a String. A String is a valid input, but I don't think that's what you intended; it seems like you want an update everytime attrs.ngTippResult changes. Instead, your current code is watching the property on the scope with the value of attrs.ngTippResult (for example, if attrs.ngTippResult was "fish", the value you would be watching with your current code would actually be $scope.fish, which probably isn't what you want.

编辑

此外,aaronfrost 的答案可能是最适合您尝试做的事情.

Also, aaronfrost's answer might be the best for what you're trying to do.

这篇关于Angular $watch 不会在我的指令中触发任何事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆