2013-08-29 101 views
0

我試圖找到一個解決以下問題:如何在更改模型屬性時爲AngularJS創建更改指令?

How to create on-change directive for AngularJS?

,我已經成立後,在的jsfiddle它的工作原理答案......但只有當財產被直接連接到$範圍。事實上,如果我

1)改變$ scope.strText至$ scope.model.strText 2),並從strText的改變屬性值model.strText

不工作了。

這裏有HTML代碼:

<div ng-controller="MyCtrl"> 
    <input on-change="model.strText"/> 
    <input on-change="model.strText"/> 
    <p>{{model.strText}}</p> 
</div> 

這裏有JS代碼:

var app=angular.module('myApp', []); 

app.directive('onChange', function() {  
    return { 
     restrict: 'A', 
     scope:{'onChange':'=' }, 
     link: function(scope, elm, attrs) {    
      scope.$watch('onChange', function(nVal) { elm.val(nVal); });    
      elm.bind('blur', function() { 
       var currentValue = elm.val();     
       if(scope.onChange !== currentValue) { 
        scope.$apply(function() { 
         scope.onChange = currentValue; 
        }); 
       } 
      }); 
     } 
    };   
}); 

app.controller('MyCtrl', function($scope) { 
    $scope.model.strText = "Hello"; 
}); 

這裏就有了的jsfiddle

http://jsfiddle.net/pmcalabrese/XbJVb/

謝謝你提前。

回答

2

您的數據源有一些缺陷,因爲$scope.model未定義。更改爲

app.controller('MyCtrl', function ($scope) { 
    $scope.model = {}; 
    $scope.model.strText = "Hello"; 
}); 
+0

完美,這裏是小提琴更新http://jsfiddle.net/pmcalabrese/XbJVb/2/ –

相關問題