簡體   English   中英

使用隔離范圍時,$ watch從內部角度指令中更改值

[英]$watch for value change from inside angular directive when using isolate scope

我試圖找到一種方法來監視對象的屬性值的變化,而該對象正在將指令的作用域限定在范圍內,而我無法弄清楚我在做什么錯。

這是我的指令代碼:

.directive('selectService', [function() {
  return {
    restrict: 'EA',
    scope: {
      distribution: '='
    },
    link: function(scope, element, attrs) {
      scope.$watch(scope.distribution.name, function(newValue) {
        console.log("Changed to " + newValue);
      });

因此,說運行時的分發是這樣的:

{ name: '', type: 'all' ... }

我想監視$ name屬性何時具有值,以便可以在指令中啟用選擇菜單。 我所做的一切似乎都不起作用。 任何幫助表示贊賞。

只需以通常的方式使用watch即可,在范圍上提供一個表示屬性的字符串或一個返回要監視值的函數。

  scope.$watch('distribution.name', function(newValue) {
    console.log("Changed to " + newValue);
  });

要在對象distribution上設置深入監視,請將watch的第三個參數設置為true。 當將scope.distribution.name提供給watch函數的第一個參數時,它將只是在不正確的scope.distribution.name值(當時)上設置watch。

演示

 angular.module('app', []).controller('ctrl', function($scope) { $scope.distribution = {}; }).directive('selectService', [ function() { return { restrict: 'EA', scope: { distribution: '=' }, link: function(scope, element, attrs) { scope.$watch("distribution.name", function(newValue) { console.log("Changed to " + newValue); }); } } } ]) 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="app" ng-controller="ctrl"> <input ng-model="distribution.name">{{distribution.name}} <div select-service distribution="distribution"></div> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM