gpt4 book ai didi

javascript - 如何在指令中调用父作用域函数

转载 作者:行者123 更新时间:2023-12-03 08:24:50 25 4
gpt4 key购买 nike

我想在指令模板中调用 Controller 函数。这不起作用:

Controller :

myApp.controller('StartController', ['$scope', '$location',  function ($scope, $location) {

$scope.changeLocation = function (path) {
$location.path(path);
}
}]);

index.html:

<div start-directive changelocation="changeLocation">
</div>

指令:

myApp.directive('startDirective', function ($templateRequest, $compile) {
return {
restrict: 'AE',
transclude: true,
link: function (scope, element, attrs) {
var baseSiteUrlPath = $("base").first().attr("href");
$templateRequest(baseSiteUrlPath + '/App/Templates/uxStart.html').then(function (html){
var template = angular.element(html);
element.append(template);
$compile(template);
});

}
};
});

和 uxStart.html

<div class="box1 square1">
<button class="indexBtn" ng-click="$parent.changeLocation('/index')">Fahrplan & Buchung</button>
</div>

<div class="box2 square2">
<button class="serviceBtn" ng-click="changeLocation('/pageNotFound')">Services</button>
</div>

我做错了什么?

提前致谢

最佳答案

您尚未使用作用域编译元素,您只创建了该模板的编译函数,例如 $compile(template),这不会编译该元素。您需要通过在其中传递作用域参数来调用编译函数。

由于您的指令使用可共享作用域,因此您无需在调用方法之前提及 $parent

指令

myApp.directive('startDirective', function($templateRequest, $compile) {
return {
restrict: 'AE',
transclude: true,
link: function(scope, element, attrs) {
var baseSiteUrlPath = $("base").first().attr("href");
$templateRequest(baseSiteUrlPath + '/App/Templates/uxStart.html').then(function(html) {
var template = angular.element(html);
element.append(template);
var linkFn = $compile(template);
//compile it with scope to generated compiled DOM with scope
linkFn(scope); //linking scope with template
});

}
};
});

关于javascript - 如何在指令中调用父作用域函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33598160/

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