2017-07-07 34 views
1

我有一个指令,我有一个模板,我试图在用户点击输入时更新ng模型。我能够抓住事件并尝试更新价值。我有元件上的观察者的控制器,但观察者功能永远不会被触发后commitViewValue

(function() { 
    'use strict'; 

    angular.module('aa') 
     .directive('ss', [ 
      function() { 

       return { 
        restrict: 'EA', 
        replace: true, 
        transclude: true, 
        scope: { 
         placeholder: '@' 
        }, 
        require: 'ngModel', 
        template: '<div class="clear">' + 

         '<input type="text" ng-model="ngModel" ng-model-options="{updateOn:\'change blur\'}" />' + 
         '</div>', 

       link: function (scope, elem, attrs, ngModelCtrl) { 
        elem.bind("keyup",function(e) { 
         if (e.keyCode === 13) { 
          e.stopImmediatePropagation(); 
          ngModelCtrl.$commitViewValue(); 
          scope.$apply(ngModelCtrl.$setTouched); 
         } 
        }); 
       } 

       } 
      } 
     ]); 
})(); 


$scope.$watch('pr', function(newValue,oldValue){ 
       console.log('val>>' + newValue); 
      }); 
<ss ng-model="pr"></ss> 

回答

1

使用$setViewValue的数据来自分离范围移动到父范围:

link: function (scope, elem, attrs, ngModelCtrl) { 
     elem.bind("keyup",function(e) { 
      if (e.keyCode === 13) { 
       e.stopImmediatePropagation(); 
       ̶n̶g̶M̶o̶d̶e̶l̶C̶t̶r̶l̶.̶$̶c̶o̶m̶m̶i̶t̶V̶i̶e̶w̶V̶a̶l̶u̶e̶(̶)̶;̶ 
       //USE $setViewValue 
       ngModelCtrl.$setViewValue(scope.ngModel); 
       //scope.$apply(ngModelCtrl.$setTouched); 
      } 
     }); 

如果您希望父控制器能够设置模型,还可以使用单向<绑定。

scope: {ngModel: '<'} 

DEMO on PLNKR

欲了解更多信息,请参阅

+0

感谢您的回答!完美的作品。 – phantomsays