Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
164
rated 0 times [  169] [ 5]  / answers: 1 / hits: 26430  / 11 Years ago, fri, july 12, 2013, 12:00:00

In my controller I've defined $scope.worker which is a plain JS object:



{
name: 'Peter',
phone: 601002003
}


I've created a directive:



.directive('phoneType', [function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
console.log(attrs);
}
};
}])


and my HTML looks like this:



<span phone-type=worker.phone></span>


How do I pass worker.phone (in this example 601002003) from the controller scope to the directive, so I can create my logic in the link method? attrs.phoneType right now shows me worker.phone string.


More From » angularjs

 Answers
137

You could also pass the value to the directive via two way binding:



.directive('phoneType', [function () {
return {
scope: {
phoneNumber: '=phoneType'
}
link: function (scope, element, attrs) {
// now do stuff with the number, you can access it through the scope
scope.phoneNumber // contains the number
}
};
}])


Now you can access the number directly through the isolate scope.
Template would look like this:



<span phone-type=worker.phone></span>


By the way, you don't need the restrict A. This is the default behavior.


[#77042] Thursday, July 11, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jimmieo

Total Points: 515
Total Questions: 102
Total Answers: 110

Location: Kazakhstan
Member since Mon, Sep 26, 2022
2 Years ago
;