【问题标题】:angular $watch parent scope variable always fired角度 $watch 父范围变量总是被触发
【发布时间】:2013-06-17 07:07:30
【问题描述】:

html

<div data-select >
     <div data-set-tip tipit='selecting(tips)' ></div>
     <div data-show-tip headsup='selectingtips' ></div>
</div>

js

directive.select= function(){
    return:{
        restrict:'A',
        controller:function($scope){
            $scope.selectingtips = '';
            $scope.selecting = function(tips){
                $scope.selectingtips = tips
            }
        }
    }
}

directive.setTip = function(){
    return {
        restrict:'A',
        scope:{
            tipit:'&'
        },
        link:function(scope,element,attrs){
            element.on('mousestop',function(){
                scope.tipit({tips:'some tips'})
            })
        }
    }

}

directive.showTip = function(){
    return {
        restrict:'A',
        scope:{
            headsup:'&'
        },
        link:function(scope,element,attrs){
            scope.$watch('headsup',function(){
                alert('changed')
            })
        }

    }
}

我希望当鼠标停在 setTip 指令上时,父指令变量 selectiontips 将被设置为某个值,并且 showTip 指令总是监听 selectiontips 的变化,并在发生变化时提醒变化。

问题

当我刷新页面时,它会立即提醒更改,当我在 setTip 指令上停止鼠标时,什么也没有发生。 注意:当鼠标停在 setTip 指令处时,选择提示确实发生了变化。

我做错了什么?

这里是 plunker link

【问题讨论】:

  • 你能提供一个 plunkr 或 fiddle 吗?
  • 检查插件

标签: angularjs scope parent watch directive


【解决方案1】:

为防止$watch 在页面加载时触发,您需要比较您正在观看的模型的新旧值:

scope.$watch('headsup',function(newVal, oldVal){
    if(newVal != oldVal)
        alert('changed')
})

查看更新的 plunker: http://plnkr.co/edit/5kJSZtVA9a8o4tRdnPaT?p=preview

【讨论】:

  • 为了防止在通过 ajax 加载数据时发生意外触发,我还必须检查 oldVal 是否与 undefined (假设数据初始化为未定义值开始): if (newVal = == oldVal || oldVal === undefined) 返回;
猜你喜欢
  • 2015-08-21
  • 2014-09-26
  • 1970-01-01
  • 2017-09-28
  • 2015-12-10
  • 2014-06-14
  • 1970-01-01
  • 2015-03-15
  • 1970-01-01
相关资源
最近更新 更多