首页 > 解决方案 > 如何将 AngularJS 指令中的值传递给父控制器中的函数

问题描述

我正在使用 Anguljarjs 1.4x。我正在尝试将外部函数的值传递回指令。我以前做过一些类似的事情,但由于某种原因,函数参数没有返回到我的控制器。

这是一些工作plunker代码,我必须将外部函数传递给指令。我现在要做的是添加一个文本参数值。

索引.html

<!DOCTYPE html>
<html>

  <head>
    <script data-require="angular.js@1.4.2" data-semver="1.4.2" src="https://code.angularjs.org/1.4.2/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <div id="app" ng-app="app">
    <div ng-controller="mainCtrl">
          <my-directive ctrl-fn="ctrlFn()"></my-directive> 
        </div>
      </div>

  </body>

</html>

我的页面.html

<div>
  <button ng-click='ctrlFn()'>Click Here</button>
</div>

脚本.js

var app = angular.module('app', []);
app.controller('mainCtrl', function($scope){
  $scope.count = 0;
  $scope.ctrlFn = function() {
      console.log('In mainCtrl ctrlFn!');
      $scope.count += 10;
      console.log("count is: " + JSON.stringify($scope.count));
  };  
});

app.directive('myDirective', function() {
  return {
    restrict: 'E',
    scope: {
      'ctrlFn' : '&'
    },
   // template: "<div><button ng-click='ctrlFn()'>Click Here</button></div>",
   templateUrl: "./myPage.html",
    link: function(scope, element, attributes) {
      scope.ctrlFn();
      console.log("In link!");
    }
  };
});

当应用程序运行时,我得到这个:在 mainCtrl ctrlFn!

计数是:10

在链接中!

单击按钮后,我得到以下信息:在 mainCtrl ctrlFn 中!

计数是:20

正如我所说,这一切都有效,直到我添加了一个参数。我要做的就是添加一个文本参数,但是当我在 myPage.html 中尝试这个时出现错误:

错误:不能使用“in”运算符在“hello”中搜索“ctrlFn”

 <button ng-click='ctrlFn('hello')'>Click Here</button>

我在我的 ng-click 函数中添加了一个文本值,然后在我列出该函数的其他地方创建了一个参数。

关于如何做到这一点的任何想法?

标签: angularjsangularjs-directive

解决方案


这是您的代码的有效工作。

https://next.plnkr.co/edit/TWQEUUWq6h55uOIXDbuR

基本上,您需要从指令中删除括号

<my-directive ctrl-fn="ctrlFn"></my-directive>   

然后在调用之前解开函数(在指令中)。

scope.ctrlFn = scope.ctrlFn();

这个答案提供了更多关于解包函数的信息。

https://stackoverflow.com/a/27300517/1896352


推荐阅读