1

i m trying to change ng-model value in custom directive but issue is that i have used controller as

<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> 

and in custom directive, i m trying to clear input field by changing ng-model value to '' but i m unable to get value

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

result is null, how can i fix this issue

any help will be appreciated

1
  • if you console.log the scope in your directive do you see a value for ngModel or clearList? Commented Feb 3, 2016 at 15:06

1 Answer 1

3

You can access the ngModel value in your custom directive by accessing the ngModel controller's $viewValue and $modelValue properties:

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
      }
    }   

 }
Sign up to request clarification or add additional context in comments.

4 Comments

thanks it provides value but i m trying to update . i have tried using ngModel.$setViewValue(null); but it doesn't work the way as expected . it doesnt update value
You should commit changes after use ngModel.$setViewValue(). $commitViewValue() - Commit a pending update to the $modelValue
You can also set model value direct - assign value to ngModel.$viewValue and then use ngModel.$commitViewValue()
i fixed it using ngModel.$render()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.