2016-01-06 60 views
0

我將範圍值傳遞給指令使用attrs。第一次加載時,我得到的未定義值爲min,但在$ watch下正常工作。 fiddleattrs value undefined in directive angularjs

link: function(scope, elm, attrs) { 
    scope.$watch(function(){return attrs.min}, function (newValue, oldValue) { 
    console.log('oldValue=' + oldValue); 
    console.log('newValue=' + newValue); 
    //do something 
    }); 
    console.log(attrs.min);      
} 
+0

您真的需要$ watch嗎?我的意思是,爲什麼不使用隔離範圍綁定? – BiAiB

+0

我可能錯過了一些東西,但問題是什麼? – miensol

+1

哦,我知道了,他想知道爲什麼'console.log(attrs.min);'返回'undefined' – BiAiB

回答

1

你爲什麼不使用$觀察呢?

app.directive('exampleDirective1', function() { 
    return { 
     restrict: 'E', 
     link: function(scope, elm, attrs) { 

     attrs.$observe('min', function(newValue) { 
      console.log(newValue); 
     }); 

    } 
}; 

});

+0

我也需要舊值 – Carlos

+0

將舊值存儲在局部變量上。在指令(或組件)中,$ observe是查看屬性的推薦方法 –

0

似乎{{message}}在指令是後鏈接之前未被評估。

你也可以使用範圍:

app.directive('exampleDirective1', function() { 
    return { 
     restrict: 'E', 
     scope: { 
      min: '=' 
     }, 
     link: function(scope, elm, attrs) { 
      scope.$watch('min', function (newValue, oldValue) { 
       console.log('oldValue=' + oldValue); 
       console.log('newValue=' + newValue); 
       //do something 
      }); 
      console.log(scope.min); 
      console.log(attrs.min); 
     } 
    }; 
}); 

而且

With template: <example-directive1 min="message"></example-directive1> 
0

嗯,這是奇怪的,由具有編譯,預鏈接和postlink有大量日誌的例子,並得到了奇怪的結果:

function MyCtrl($scope) { 
    $scope.message = 'hello'; 
    console.log('$scope.message set to hello'); 
} 

app.directive('exampleDirective1', function() { 
    return { 
     restrict: 'E', 
     compile: function(tElement, tAttrs) { 
      console.log('currently at compile, attrs.min = ', tAttrs.min); 

      return { 
       post: function postLink(scope, elm, attrs) { 
       scope.$watch(function(){return attrs.min}, function (newValue, oldValue) { 
        console.log('currently, attrs.min = ', attrs.min); 
       }); 
       console.log('currently at postlink, attrs.min = ', attrs.min);      
       }, 
       pre: function prelink(scope,elm , attrs) { 
       console.log('currently at prelink, attrs.min = ', attrs.min); 
       } 
      }; 
     } 
    }; 
}); 

http://jsfiddle.net/qdzLhpf9/

預鏈接運行時,範圍值已經設置。但是,這些論點似乎是在後鏈接和預鏈接之間進行評估的。

編輯: 經過一些更多的挖掘,似乎像$編譯初始化args到'undefined'在你的角度版本。請參閱https://code.angularjs.org/1.0.0/angular-1.0.0.js在4434行。