在angular中,如何调用指令控制器内定义的函数?

时间:2016-07-29 11:34:51

标签: angularjs angularjs-directive angularjs-scope

以下是代码:

指令代码:



angular.module('app', ['localytics.directives', 'ngLoadScript'])
.directive("home", function() {
	return {
		restrict: "A",
		replace: true,
		template: "<div ng-include='var'>{{var}}</div>",
		controller: function($scope) {
			//loading home page - as default
			$scope.var = "/tfm/home.html"
			//on change the page changed dynamically!
			$scope.change = function(where) {
				$scope.var = where;
			}
		}
	}
})
&#13;
&#13;
&#13;

我想调用指示(在哪里)指令的功能 - 在指令控制器中定义。

控制器代码:

&#13;
&#13;
.controller('wToEatController', ['$scope', function($scope) {
	$scope.submitInfoAboutTable = function() {
		//validation for time selection
		if($scope.idealTableTime == undefined || $scope.rightTableTime == undefined) {
			return;
		}
		
		//Booking details to be updated - here users preference is updating!
		var bookingDetails = {
			idealTableWaitTime: $scope.idealTableTime,
			rightTableWaitTime: $scope.rightTableTime
		}
		
		//Let's update booking information - the booking key will be same used while login, public/tfm.html
		FirebaseDbService.updateBooking(function(isUpdated) {
			console.log(isUpdated);
			//I WANT TO CALL chanage(where) function of DIRECTIVE
			$scope.change = "change('/tfm/home.html')";
		}, bookingDetails, bookingKey);
	}	
}]);
&#13;
&#13;
&#13;

有可能吗?

1 个答案:

答案 0 :(得分:2)

您必须创建一个用于完成链接的属性(在此示例中为customAttr):

<span yourDirectiveName  customAttr="myFunctionLink(funcInDirective)"></span>  

在您的指令控制器中,只需设置新属性,如下面的代码段('&'双向数据绑定),并使用指令方法创建连接:

scope : {customAttr : '&'},
link : function(scope,element,attrs){

        scope.myDirectiveFunc = function(){
             console.log("my directive function was called");}
        }
        scope.customAttr({funcInDirective : scope.myDirectiveFunc});
}

在你的控制器中:

$scope.myFunctionLink = function(funcInDirective){
$scope.callableDirectiveFunc = funcInDirective;}

现在您可以使用$scope.callableDirectiveFunc();

调用指令函数