【问题标题】:AngularJS : Call controller function from a directive with isolated scopeAngularJS:从具有隔离范围的指令调用控制器函数
【发布时间】:2014-10-15 10:46:42
【问题描述】:

我有以下问题。我想从具有隔离范围的指令中调用控制器函数。

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

【问题讨论】:

    标签: javascript angularjs angularjs-directive angularjs-scope


    【解决方案1】:

    您可以使用&amp; 之类的方式传递要调用的函数

    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>

    【讨论】:

      猜你喜欢
      • 2013-07-09
      • 2019-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多