Reputation: 4292
I have angularjs directive with template which consists of two tags - input and the empty list. What I want is to watch input value of the first input tag. The $watch()
method is called once when directive is initialised but that's it. Any change of input value is silent. What do I miss?
here is my plunk
and here is the code:
.directive('drpdwn', function(){
var ref = new Firebase("https://sagavera.firebaseio.com/countries");
function link(scope, element, attrs){
function watched(){
element[0].firstChild.value = 'bumba'; //this gets called once
return element[0].firstChild.value;
}
scope.$watch(watched, function(val){
console.log("watched", val)
}, true);
}
return {
scope:{
searchString: '='
},
link: link,
templateUrl:'drpdwn.html'
}
})
Edit:
if I call $interval()
within link function it works as expected. is this intentional behaviour?
Upvotes: 0
Views: 95
Reputation: 759
You are setting the the value you want in the watcher function.
function watched(){
element[0].firstChild.value = 'bumba'; //this gets called once
return element[0].firstChild.value;
}
is essentially the same return value as
function watched() {
return 'bumba';
}
So the watcher will always return the same value.
If you want to initialize the value. Do it outside of the watcher:
element[0].firstChild.value = 'bumba'; //this gets called once
function watched(){
return element[0].firstChild.value;
}
Upvotes: 0
Reputation: 4302
It doesn't get called because there is never a digest triggered on the scope.
Try this instead, using ng-model:
http://plnkr.co/edit/qMP5NDEMYjXfYsoJtneL?p=preview
function link(scope, element, attrs){
scope.searchString = 'bumba';
scope.$watch('searchString', function(val){
console.log("watched", val)
val = val.toLowerCase();
val = val.replace(/ */g,'');
var regex = /^[a-z]*$/g;
if (regex.test(val)) {
scope.searchString = val;
// TODO something....
}
}, true);
Template:
<input class="form-control" ng-model="searchString" id="focusedInput" type="text" placeholder="something" />
<div></div>
Upvotes: 1