角$表并不在我的指令触发任何情况 [英] Angular $watch does not fire any event in my directive

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

问题描述

我尝试更新元素的内容取决于我的自定义指令的属性值。低于code在现场负载运行良好,但只有一次。在属性值动态更新不火的任何事件。我该怎么办错了?

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?

纳克重复内的标记(在比赛中赛):

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);
            });
        }
    };
});

编辑:

,我遇到了一个无穷远消化循环与上面的code。

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.

推荐答案

$第一个参数看应该是你想要观看价值的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.ngTip presult 正在评估为String。一个字符串,是一个有效的输入,但是我不认为那是你的本意;好像你想更新每次 attrs.ngTip presult 的变化。相反,当前的code是看示波器上的财产attrs.ngTip presult的值(例如,如果attrs.ngTip presult是,你将与你目前的code注视实际上是值 $ 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.

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

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