HTML
angular.element(document.querySelector('#dateControls')).append($compile("<search-date></search-date>")($scope));
指令
myApp.directive('searchDate', function ($compile, $rootScope,$timeout) {
var linker = function (scope, element, attrs) {
var template = '<button class="btn btn-default" ng-click="dateSearch() id="playbackSearch" search-date">Search</button>';
element.html(template);
$compile(element.contents())(scope);
};
return {
restrict: "EA",
replace: true,
link: linker
};
});
Controller
$scope.dateSearch = function(){
scope.userId = 1;
myModuleService.getData(userId) //call service
then(function (data) {
console.log(data);
}).catch(function (error) {
throw error;
});
};
如何调用 Controller 中定义的函数 dateSearch()
?
最佳答案
您可以在指令本身中添加 Controller 。因为您的 myModuleService
是外部服务
喜欢
controller:function($scope,myModuleService)
{
$scope.dateSearch = function(){
scope.userId = 1;
myModuleService.getData(userId) //call service
then(function (data) {
console.log(data);
}).catch(function (error) {
throw error;
});
};
}
或按照您的风格
var controll:function($scope,myModuleService)
{
$scope.dateSearch = function(){
scope.userId = 1;
myModuleService.getData(userId) //call service
then(function (data) {
console.log(data);
}).catch(function (error) {
throw error;
});
};
}
return {
restrict: "EA",
replace: true,
link: linker,
controller:controll
};
关于javascript - AngularJS - 从指令调用 Controller 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38930119/