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



这是代码:

指令代码:

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;
			}
		}
	}
})

我想调用指令的chanage(where)函数-在指令的控制器中定义。

控制器代码:

.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);
	}	
}]);

有可能吗

您必须创建一个用于进行链接的属性(在本例中为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(); 调用指令函数

最新更新