angular attrs.$observe和$scope.$watch的區別

世有因果知因求果發表於2015-09-05

  http://stackoverflow.com/questions/14876112/difference-between-the-observe-and-watch-methods

https://docs.angularjs.org/api/ng/type/$compile.directive.Attributes

$observe()是Attributes 物件的一個方法,它只能用於observe/watch一個DOM attribute的value change.它只在directive內部被呼叫。當你需要監察、偵聽一個包含interpolation的attribute的DOM時,你需要使用$observe()函式(比如:{{attrValue}},再比如select控制元件,當你選擇一個option時,如果對應的屬性作為觸發過濾結果集這種場景時,可以$observe這個選擇動作的結果(作為attr)

<div d1 attr1="{{prop1}}-test" attr2="prop2" attr3="33" attr4="'a_string'"
        attr5="a_string" attr6="{{1+aNumber}}"></div>

 

$watch被用於監察、偵聽一個model/scope屬性,比如:scope.$watch(attrs.attr1)...

注意:angular normalize string

相關文章