Passing variable from controller scope to directive
26,293
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.
Related videos on Youtube
Author by
acid
Updated on July 05, 2022Comments
-
acid about 2 years
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 thelink
method?attrs.phoneType
right now shows meworker.phone
string. -
pixelbits about 10 yearsI much prefer this solution
-
Maxim Zubarev over 8 yearsscope.phoneType won't update though if worker.phone updates. Is there a solution for this?
-
bluenavajo about 8 years@thelamborghinistory It depends on where you use the phonyType scope property. If you solely use it in the directive's view it should update automatically due to the two-way binding nature. If you want to trigger other actions in the directive controller you have to set up a $watch on the scope property in order to be notified when the property changes. Does this help? Feel free to provide a jsFiddle, which describes your problem.