Reputation: 23483
How can I call angular function inside directive which is defined in controller?
var app = angular.module('myApp', ['ngResource']);
app.directive('hello', function () {
return {
scope: {
myObj: '=hello'
},
template: '<button class="btn btn-primary" ng-click="dirFunction()">Click</button>',
link: function (scope) {
scope.dirFunction = function () {
scope.count++;
console.log('I am dirFunction');
};
var countChange = function (someVar) {
console.log('I am countChange');
// scope.changeCount(someVar); // call changeCount() defined in controller
};
// scope.$watch('myObj', hello);
scope.$watch('count', countChange);
}
}
});
function MyCtrl($scope) {
$scope.message = 'Can I do it?';
$scope.myObj = {data:'I need this data object',count:1};
$scope.changeCount = function(someVar) {
console.log("I am changeCount from controller,I have someVar in hand");
}
}
I need to call the commented scope.changeCount(someVar);
in directive.
See HTML,
<div ng-app="myApp">
<div class="container" ng-controller="MyCtrl">
<div class="row">
{{message}}
<div hello="myObj"></div>
</div><!--/row-->
</div>
</div>
Upvotes: 2
Views: 857
Reputation: 43957
Use &
while invoking a controller function on the parent scope from inside a directive using an isolate scope:
<div hello="myObj" change-count="changeCount(someVar)"></div>
app.directive('hello', function () {
return {
scope: {
myObj: '=hello',
changeCount:"&changeCount"
},
template: '<button class="..." ng-click="dirFunction()">Click</button>',
link: function (scope) {
scope.dirFunction = function () {
scope.myObj.count++;
console.log('I am dirFunction '+scope.myObj.count);
};
var countChange = function (someVar) {
console.log('I am countChange '+someVar);
scope.changeCount({'someVar':someVar});
};
scope.$watch('myObj.count', function(newValue){
countChange(newValue)
});
}
}
});
Upvotes: 3