2013-06-20 80 views
0

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指令父指令變量selectingtips將被設置的東西,並且showTip指令總是聽取選擇提示的變化,並且當更改發生警報更改時。

問題

當我刷新它會立即發出警告更改頁面,當我停止setTip指令鼠標,什麼都不會發生。 注意:當鼠標停在setTip指令時,選擇提示確實發生了變化。

我做錯了什麼?

這裏是plunker link

+0

您能提供一個plunkr或小提琴嗎? – Narretz

+0

檢查plunker – paynestrike

回答

3

爲了防止$watch從射擊頁面加載,你會需要比較模型的新舊值你看:

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

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

+0

爲了防止在通過ajax加載數據時發生不必要的觸發,我必須檢查oldVal是否還未定義(假定數據已初始化爲非未定義的值以開始):if(newVal === oldVal || oldVal === undefined)return; – Daniel