如何从控制器中的指令调用函数? AngularJS
问题描述:
如何在控制器中可以通过指令调用函数clearCopy
?如何从控制器中的指令调用函数? AngularJS
这是我的HTML的一部分:
<tr ng-form="mForm" my-directive>
<td>
<div>
<button class="btn btn-default" ng-click="saveData(row)"> </button>
</div>
</td>
</tr>
这是我的指令:
angular.module("w.forms").directive("myDirective", function() {
return {
require: ["^form"],
link: function (scope, element, attrs, ctrls) {
scope.$watch(function() {
// ...... something
}, true);
scope.clearCopy = function() {
// do something
}
}
};
});
这是我的控制器:
angular.module("app").controller("datalesController", function ($scope) {
$scope.saveData(row) = function {
// do something then run function from directive
// till this part everything works fine
$scope.clearCopy() // unfortunately it doesn't work :(
}
}
一切工作正常,但功能$scope.clearCopy()
在控制器不起作用。
答
HTML
<html>
<script src="library/angular.min.js"></script>
<script src="practice.js"></script>
<head>
</head>
<body ng-app="app" ng-controller="datalesController">
<div my-directive>
<button ng-click="saveData()">press </button>
</div>
</body>
</html>
控制器
angular.module('app',[]).controller("datalesController", function ($scope) {
$scope.saveData = function() {
// do something then run function from directive
// till this part everything works fine
$scope.clearCopy(); // unfortunately it doesn't work :(
};
});
指令
angular.module('app',[]).directive("myDirective" , function() {
return {
restrict:'A',
link: function (scope, element, attrs, ctrls) {
scope.clearCopy = function() {
console.log("calling from controller");
};
}
};
});
我改变你的代码来运行你的要求
http://*.com/questions/16881478/how-to-call-a-method-defined-in-an-angularjs-指令可能会有所改变。 – Jason
您的指令模块和控制器模块不同。 –