Angular js - 在custom指令中更改模型的值

时间:2016-02-03 14:59:35

标签: angularjs

我试图在自定义指令中更改ng-model值,但问题是我使用了控制器作为

<div ng-controller="AreaController as vm">
<md-input-container flex="40" class="md-block" on-enter="vm.search()">
            <label>Search</label>  
              <md-icon class="material-icons" >search</md-icon>  
            <input type="text" name="search" ng-model="vm.area.searchText" clear-input="vm.getList()">
            </md-input-container> 

在自定义指令中,我试图通过将ng-model值更改为''来清除输入字段,但我无法获得值

   var result = scope[attr.ngModel];
                    var r = $parse(attr.ngModel);

结果为空,我该如何解决这个问题

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:3)

您可以访问ngModel控制器的ngModel$viewValue属性来访问自定义指令中的$modelValue值:

angular.module('app').directive('clearInput', clearInputDirective)

var clearInputDirective = function(){
    return {
      restrict: "A",
      require: "ngModel",
      link: function(scope, element, attr, ngModel){
         var view_value = ngModel.$viewValue; //The actual value from the control's view
         var model_value = ngModel.$modelValue; //The value in the model that the control is bound to
         ngModel.$viewValue = 'new value'; //Set new view value
         ngModel.$commitViewValue(); //Commit a pending update to the $modelValue
      }
    }   

 }