Anton Anton - 6 months ago 16
Javascript Question

Access property of isolated scope from directive

How can I access isolated scope's property in directive tag?
Simplified example:



angular.module('app', [])
.controller('myController', function() {
var result_el = document.getElementById("result");
this.log = function(text) {
var p = document.createElement("p");
p.innerHTML = text;
result_el.appendChild(p);
}
})
.directive('myDirective', function() {
return {
restrict: 'E',
scope: {
'click_fn': '&myClick'
},
template: '<span ng-click="click_fn()">Click me!</span>',
link: function(scope, element) {
scope.my_prop = 'text property';
}
}
});

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>

<div ng-app="app" ng-controller="myController as mCtrl">
<my-directive my-click="mCtrl.log(my_prop)"></my-directive>
</div>
<div id="result"></div>





In this example I need to get
my_prop
property from directive's scope. Is it possible to do this somehow?

Answer

The directive definition object for isolate scope (DDO)should be as below

 scope: {
         click_fn: '&myClick' // click_fn should not be string 
       },

In directive template , need to pass parameter in object literal (aliasing)as below

Directive template

template: '<span ng-click="click_fn({my_prop:my_prop})">Click me!</span>'

Plunker