I'm writing one of my first directives and I want to create some stub data in directive's scope.
Here is directive:
angular.fraskDirectives.directive("recipientsSelector", [
function() {
return {
restrict: "E",
replace: true,
scope: {
recipients: "=",
theText: "test",
users: [{
username: "aaa"
}, {
username: "aab"
}, {
username: "abb"
}, {
username: "bbb"
}, {
username: "bbc"
}]
},
templateUrl: "partials/recipientsSelector.html"
};
}
]);
and here is template:
<div>
<div contenteditable>
<p>{{theText}}</p>
</div>
<ul class="suggestions">
<li ng-repeat="user in users">
{{user.username}}
</li>
</ul>
But neither "text" field nor user field are not bound. I mean ul is empty and {{text}}
looks like " {{text}}
" on the page.
How could I create local data in my directive's isolated scope?
Thanks
To populate the scope with only "local" data which is not bound to anything outside the directive, use a link function like below:
angular.fraskDirectives.directive("recipientsSelector", [ function() {
return {
restrict: "E",
replace: true,
scope: {
recipients: "=" // note that theText and users are missing
},
templateUrl: "partials/recipientsSelector.html",
link: function (scope, elem, attrs) {
scope.theText = "test";
scope.users = [{
username: "aaa"
}, {
username: "aab"
}, {
username: "abb"
}, {
username: "bbb"
}, {
username: "bbc"
}];
}
};
}]);
An alternative would be to assign a controller to the directive and populate the scope in the controller.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.