Directive exposing behavior
HTML
<script src="http://code.angularjs.org/1.1.0/angular.min.js"></script>
<div ng-app="main">
<div ng-controller="MyCtrl">Click the first button and everything is ok:
<br>
<button ng-click="callFnInAttribute()">Call Function in Attribute Directive</button>
<br>{{errorViaAttribute}}
<div my-attribute my-fn-via-attribute="fnInCtrlViaAttribute"></div>
<br>
<br>But click the second button and you get an error:
<br>
<button ng-click="callFnInElement()">Call Function in Element Directive</button>
<br>{{errorViaElement}}
<my-element my-fn-via-element="fnInCtrlViaElement"></my-element>
<br>
<br>The only difference is the type of directive used. Why does it work with an Attribute type of directive but not with an Element directive?</div>
</div>
JavaScript
angular.module("main", []).controller("MyCtrl", function ($scope) {
$scope.callFnInAttribute = function () {
try {
$scope.fnInCtrlViaAttribute();
$scope.errorViaAttribute = "OK";
} catch (anError) {
$scope.errorViaAttribute = "Error: " + anError;
}
};
$scope.callFnInElement = function () {
try {
$scope.fnInCtrlViaElement();
$scope.errorViaElement = "OK";
} catch (anError) {
$scope.errorViaElement = "Error: " + anError;
}
};
}).directive("myAttribute", function () {
return {
require: 'A',
scope: {
myFnViaAttribute: '='
},
controllerAs: 'chartCtrl',
bindToController: true,
controller: function ($scope) {
$scope.myFnViaAttribute = function () {
console.log("myFnViaAttribute called");
}
}
};
}).directive("myElement", function () {
return {
require: 'E',
scope: {
myFnViaElement: '='
},
controllerAs: 'chartCtrl',
bindToController: true,
controller: function ($scope) {
$scope.myFnViaElement = function () {
console.log("myFnViaElement called");
}
}
};
});