angularjs - Passing a model to a custom directive - clearing a text input -


what i'm trying achieve relatively simple, i've been going round in circles long, , it's time seek help.

basically, have created directive comprised of text input , link clear it.

i pass in id via attribute works in fine, cannot seem work out how pass model in clear when reset link clicked.

here have far:

in view:

<text-input-with-reset input-id="the-relevant-id" input-model="the.relevant.model"/> 

my directive:

app.directive('textinputwithreset', function() {    return {       restrict: 'ae',       replace: 'true',       template: '<div class="text-input-with-reset">' +                   '<input ng-model="inputmodel" id="input-id" type="text" class="form-control">' +                   '<a href class="btn-reset"><span aria-hidden="true">&times;</span></a>' +                 '</div>',       link: function(scope, elem, attrs) {         // set id of input clickable labels (works)         elem.find('input').attr('id', attrs.inputid);          // reset model , clear text field (not working)         elem.find('a').bind('click', function() {           scope[attrs.inputmodel] = '';         });       }   };  }); 

i'm missing fundamental - appreciated.

you should call scope.$apply() after resetting inputmodel in function reset value.

elem.find('a').bind('click', function() {       scope.inputmodel = '';       scope.$apply();     }); 

please, read scope in angularjs here.

$apply() used execute expression in angular outside of angular framework. (for example browser dom events, settimeout, xhr or third party libraries). because calling angular framework need perform proper scope life cycle of exception handling, executing watches.

i've added declaring of inputmodel attribute in scope of directive.

scope: {     inputmodel: "="   } 

see demo on plunker.

but if can use ng-click in template - use it, it's better.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -