【发布时间】:2019-01-22 17:24:36
【问题描述】:
我正在使用 Anguljarjs 1.4x。我正在尝试将外部函数的值传递回指令。我以前做过一些类似的事情,但由于某种原因,函数参数没有返回到我的控制器。
这是一些有效的plunker 代码,我必须将外部函数传递给指令。我现在要做的是添加单个文本参数值。
index.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>
myPage.html
<div>
<button ng-click='ctrlFn()'>Click Here</button>
</div>
script.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 函数中添加了一个文本值,然后在我列出该函数的其他地方创建了一个参数。
关于如何做到这一点的任何想法?
【问题讨论】:
-
将
<button ng-click='ctrlFn('hello')'>更改为<button ng-click="ctrlFn({$event:'hello'})">
标签: angularjs angularjs-directive