Reputation: 53
I created a angular directive in my main javascript file.
myApp.directive('mymin', function(){
var func = function(scope, im, attrss, c){
scope.$watch(function(){ return im.attr('ng-minlength') }, function(n){
scope.min = n
})
}
return {link:func, restrict: 'A'}
});
I just want to watch the value state of "ng-minlength". I put this directive in one html file
Html:
<input type="text" mymin ng-minlength=5>
<input type="text" mymin ng-minlength=13>
I thought that when I change the focus from one input to another one, the value of "scope.min" will be changed, but i am wrong. The value of "scope.min" is alway 13.
So could you tell me the reason? Thank you very much.
Upvotes: 0
Views: 80
Reputation: 6666
If you wish to watch for changes on element attributes then rather than $watch you should be using $observe on the attributes object(The third parameter of the link function)
attrss.$observe("ng-minlength", function(n){
scope.min = n
})
Upvotes: 1
Reputation: 388316
If you want to update scope.min
of blur of the element, use a blur event handler
var app = angular.module('my-app', [], function() {})
app.controller('AppController', function($scope) {
$scope.message = "Welcome";
});
app.directive('mymin', function() {
var func = function(scope, im, attrss, c) {
angular.element(im).on('blur', function() {
scope.min = im.attr('ng-minlength');
scope.$apply();
})
}
return {
link: func,
restrict: 'A'
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="my-app">
<div ng-controller="AppController">
<p>{{min}}</p>
<input type="text" mymin ng-minlength=5 />
<input type="text" mymin ng-minlength=13 />
</div>
</div>
Upvotes: 0
Reputation: 4506
<input type="text" mymin ng-minlength=5>
This line will create a mymin
directive acting for this particular input element - the min-length on this input will not change, it's always 5. (You seem to assume that the directive will be the same one instance on every element you place it on, this is not the case)
If you want 1 directive to watch and manage the state of every input, create a custom directive for the element containing all these inputs.
Upvotes: 0
Reputation: 3944
you can do rather like this:-
If you want to watch directive attribute
myApp.directive('mymin', function(){
var func = function(scope, im, attrss, c){
scope.$watch('ngMinlength', function(n){
scope.min = n
})
}
return {link:func, restrict: 'A'}
});
Upvotes: 0