gpt4 book ai didi

angularjs - 在执行 Controller 之前让 AngularJS 编译指令和链接函数

转载 作者:行者123 更新时间:2023-12-02 22:19:06 24 4
gpt4 key购买 nike

由于我的程序的性质,我要求将函数放置在作用域上并在指令的链接函数和 Controller 之间共享,就像这样......

.controller("controller", function($scope, $location, $timeout, model) {

//irrelevant code

$scope.addObject(draggables[i]);

};


.directive("designCanvas", function($timeout) {
return {
restrict: "A",
link: function($scope, element) {

$scope.addObject = function(draggable) {

// irrelevant code
}
}
}
}

当我调用此函数时,我得到“$scope.addObject 不是函数”。

我的问题是 Controller 在 angularJS 评估链接函数之前执行,因为当我使用 $timeout 延迟几秒钟时函数调用工作正常

所以我的问题是,如何才能首先编译链接函数的内容?

最佳答案

我建议将此函数编写为服务并将该服务注入(inject)指令和 Controller 中。 共享功能应作为服务实现。

.factory("objectService",function(){
return {
addObject : function (draggable){
//your code of this function
}
};
});

.controller("controller", function($scope, $location, $timeout, model,objectService) {

//irrelevant code

$scope.addObject = function (draggable){
objectService.addObject(draggable); //reuse this function
//objectService.addObject.call($scope,draggable) if you want to call this function with $scope as the context.
};
};

.directive("designCanvas", function($timeout,objectService) {
return {
restrict: "A",
link: function($scope, element) {
$scope.addObject = function(draggable) {
objectService.addObject(draggable); //reuse this function.
//objectService.addObject.call($scope,draggable) if you want to call this function with $scope as the context.

//write more logic specific to this function, like modifying link's local data.
}
}
}
}

关于angularjs - 在执行 Controller 之前让 AngularJS 编译指令和链接函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20921705/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com