简体   繁体   English

AngularJS:从具有隔离范围的指令中调用控制器函数

[英]AngularJS : Call controller function from a directive with isolated scope

I have the following problem. 我有以下问题。 I would like to call controller function from a directive with isolated scope. 我想从具有隔离范围的指令中调用控制器功能。

HTML: HTML:

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

JS: 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>"
    };
});

When directive don't have an isolated scope, the call function follows. 当指令没有孤立的作用域时,将调用call函数。

Working DEMO 工作演示

You can pass the function to be called using & like 您可以使用& like传递要调用的函数

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM