gpt4 book ai didi

javascript - Angular : Call controller function from a directive with isolated scope

转载 作者:行者123 更新时间:2023-11-30 10:11:30 25 4
gpt4 key购买 nike

我有以下问题。我想从具有隔离作用域的指令调用 Controller 函数。

HTML:

<div ng-controller="MainController">
<test></test>
</div>

JS:

var app = angular.module("app", []);

app.controller("MainController", function ($scope) {
$scope.testFunction = function () {
console.log("You just call testFunction()!");
};
});

app.directive("test", function () {
return {
restrict: "E",
scope: {},
template: "<h1 ng-click='testFunction()'>Hello world!</h1>"
};
});

当指令没有独立作用域时,调用函数紧随其后。

Working DEMO

最佳答案

您可以使用 & 传递要调用的函数,例如

var app = angular.module("app", []);

app.controller("MainController", function($scope) {
$scope.counter = 0;
$scope.testFunction = function() {
$scope.counter++;
};
});

app.directive("test", function() {
return {
restrict: "E",
scope: {
myfn: '&myfn'
},
template: "<h1 ng-click='myfn()'>Hello world!</h1>"
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MainController">
<test myfn="testFunction()"></test>
<span>{{counter}}</span>
</div>

关于javascript - Angular : Call controller function from a directive with isolated scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26380630/

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