12

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.

acid
  • 2,099
  • 4
  • 28
  • 41

1 Answers1

26

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.

bluenavajo
  • 483
  • 5
  • 9
  • I much prefer this solution – Michael Kang May 29 '14 at 05:12
  • scope.phoneType won't update though if worker.phone updates. Is there a solution for this? – Maxim Zubarev Jan 29 '16 at 19:22
  • @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. – bluenavajo Apr 25 '16 at 10:08