[英]Call controller function from angular directive
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);
我需要调用注释的scope.changeCount(someVar);
in directive. 在指令中。
See HTML, 参见HTML,
<div ng-app="myApp">
<div class="container" ng-controller="MyCtrl">
<div class="row">
{{message}}
<div hello="myObj"></div>
</div><!--/row-->
</div>
</div>
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)
});
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.