關(guān)于$watch 的問題
? ? ? ? angular.module("exampleApp",[])
? ? ? ? ? ? ? ? .directive("unorderedList",function(){
? ? ? ? ? ? ? ? ? ? ? ?return function(scope, element, attrs){
? ? ? ? ? ? ? ? ? ? ? ? ? ?var data= scope[attrs["unorderedList"]];
? ? ? ? ? ? ? ? ? ? ? ? ? ?var propertyExpression = attrs["listProperty"];
? ? ? ? ? ? ? ? ? ? ? ? ? ?if(angular.isArray(data)){
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?var listElem = angular.element("<ul>");
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?element.append(listElem);
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?for(var i=0; i< data.length; i++){
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?(function(){
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?var itemElement =angular.element("<li>");
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?listElem.append(itemElement);
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?var index = i;
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?var watcherFn = function(watchScope){
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?console.log("watcherFn: " +index +" ?"+data[index].name);
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?return ?watchScope.$eval(propertyExpression, data[index]);
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?scope.$watch(watcherFn, function(newValue,oldValue){
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?console.log("$watch: "+index);
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?itemElement.text(newValue);
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?});
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?}())
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? })
誰能解釋一下 $watch中第一個參數(shù)如果是個函數(shù) 那么應(yīng)該怎么判定 它是否發(fā)生了變化,因為我嘗試過 讓這個函數(shù)每次的返回值都一樣 ,可是我發(fā)現(xiàn) 即便如此$watch的第二個參數(shù)還是被觸發(fā)了。
2017-03-17
你的$watch檢測watcherFn這個函數(shù),$watch會調(diào)用$parse解析,將解析后的結(jié)果通過調(diào)用$$watchDelegate來判斷你的新老值的變化,在angular.js的12977行你設(shè)個斷點調(diào)試下,看值有啥變化