2014-01-21 35 views
0

如果用戶輸入不是數字,我必須恢復到舊數值。角度指令範圍[attrs.ngModel]不起作用

從指令設置範圍值不起作用。

http://jsfiddle.net/vfsHX/149/

app.directive('isNumber', function() { 
    return { 
    require: 'ngModel', 
     link: function (scope, element, attrs) { 
      scope.$watch(attrs.ngModel, function(newValue,oldValue) { 
      var arr = String(newValue).split(""); 
      if (arr.length === 0) return; 
      if (arr.length === 1 && (arr[0] == '-' || arr[0] === '.')) return; 
      if (arr.length === 2 && newValue === '-.') return; 
      if (isNaN(newValue)) { 
       console.log(oldValue); 
       scope[attrs.ngModel] = oldValue; 
      } 
     }); 
    } 
}; 
}); 

回答

0

你的模型是嵌套形式,因此當您嘗試使用scope[attrs.ngModel]訪問,你referening到模型,該模型是不存在。如果你直接給它一個引用然後它的工作,而不是使用嵌套的javascript模型。看看這裏的小提琴http://jsfiddle.net/ztUsc/1/

+0

但我真的想這樣做,嵌套的JavaScript模型。怎麼做? – Thilaga