[英]AngularJS - Call Controller function from Directive
的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
};
});
控制者
$scope.dateSearch = function(){
scope.userId = 1;
myModuleService.getData(userId) //call service
then(function (data) {
console.log(data);
}).catch(function (error) {
throw error;
});
};
如何调用控制器中定义的dateSearch()
函数?
您可以在指令本身中添加控制器。 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
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.