I'm trying to create a directive and am running into some problems with the scope object. In creating a plunkr to display what is happening I noticed that I'm close, but not quite sure what I'm misunderstanding.
If i have a directive that looks like this:
angular.module('inputExample', [])
.directive('test',
function() {
return{
restrict: 'E',
link: function(scope){
scope.testInput = 1;
scope.$watch(
'testInput',
function(newTestInput){
console.log(newTestInput);
},
false);
}
}
});
And utilize the directive in the view like this:
<test>
<input data-ng-model="testInput" />
<div>
{{testInput}}
</div>
the div seems to be updated correctly and there is a message logged to the console as I would expect.
If I create the directive like this though:
angular.module('inputExample', [])
.directive('example',
function() {
return{
scope: {
'settings': '@'
},
restrict: 'E',
link: function(scope){
scope.exampleInput = 1;
scope.$watch(
'exampleInput',
function(newTestInput){
console.log(newTestInput);
},
false);
}
}
});
</test>
and use it in a view like this:
<example>
<input data-ng-model="exampleInput" />
<div>
{{exampleInput}}
</div>
</example>
then the div seems to get updated, but there is no message logged to the console. It seems as though the $watch isn't working. Can someone please tell me what I'm doing wrong?
Here is the plunkr.
Thanks in advance for any help that can be offered.
-
Why do you set 'settings' in the directive's scope? you don't seem to use it at all.DevLounge– DevLounge2014年09月29日 19:38:14 +00:00Commented Sep 29, 2014 at 19:38
-
In this example I don't, but my actual scenario is using the settings. I can update the plunkr to reflect that, but that didn't seem to matter in causing this to happen.peinearydevelopment– peinearydevelopment2014年09月29日 19:44:40 +00:00Commented Sep 29, 2014 at 19:44
-
Ok, no issue, I was just wondering.DevLounge– DevLounge2014年09月29日 19:47:10 +00:00Commented Sep 29, 2014 at 19:47
1 Answer 1
The problem with the example is that you're putting your HTML inside your directive tags. They should be in your template.
This code works
angular.module('inputExample', [])
.directive('example',
function() {
return{
scope: {
'settings': '@'
},
restrict: 'E',
template: '<input data-ng-model="exampleInput" /><div>{{exampleInput}}</div>',
link: function(scope){
scope.exampleInput = 1;
scope.$watch(
'exampleInput',
function(newTestInput){
console.log(newTestInput);
},
false);
}
}
});
With the view as just
<example></example>
4 Comments
example directive, then it works. But @peinearydevelopment specified a need for the isolate scope in one of the comments.Explore related questions
See similar questions with these tags.