Search code examples
angularjsangularjs-directivejqlite

Adding watch to directive inner element.val() even without ngModel


---html---
<input-wrap>
<input type="text"/>
</input-wrap>

---js---
myModule.directive('inputWrap',function(){
   return{
       restrict: 'E',
       priority: 0,
       link: function(scope,element,attr){
           var myInput = element.find('input');
           scope.$watch(myInput.val(),function(val){
                 console.log('recipe is now:'+val);
           });
       }
   }
});

I want to do this even without the help of on('change') and on('input') because the value is sometimes modified by the plugin I used, and it doesn't fire onChange and onInput events.


Solution

  • Write your watcher like :

    myModule.directive('inputWrap',function(){
    return{
       restrict: 'E',
       priority: 0,
       link: function(scope,element,attr){
           var myInput = element.find('input');
           scope.$watch(function() { return myInput.val() },function(val){
                 console.log('recipe is now:'+val);
           });
       }
     }
    });