Jaseem Abbas
Jaseem Abbas

Reputation: 5230

Angular : How to get parent and element scope in directive

.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
            scope.vm.somethingInMyController // vm is undefined
        }
    };
}])

How do I achieve both phoneType and the vm variable in my directive?

Upvotes: 0

Views: 221

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136134

As you want to directive to be having isolated scope, you should pass required data to directive to its scope properties only via its attribute. Accessing parent(using $parent) scope from directive will make it tightly couple with parent scope assuming some naming convention.

Markup

<div phone-type 
   phone-number="vm.myPhoneNumber" 
   something-more="vm.somethingInMyController">
</div>

Directive

scope: {
   phoneNumber: '=phoneType',
   somethingMore: '=' //pass more data here
}

Upvotes: 1

Related Questions