我使用的是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
在链接中!
在我点击按钮后,我得到了这个: In mainCtrl ctrlFn!
计数为: 20
正如我所说的,这一切都是有效的,直到我添加了一个参数。我所要做的就是添加一个文本参数,但是当我在myPage.html中尝试这样做时,我得到了一个错误:
错误:无法使用' in‘运算符在'ctrlFn’中搜索'hello‘
<button ng-click='ctrlFn('hello')'>Click Here</button>
我在ng-click函数中添加了一个文本值,然后在列出该函数的其他位置创建了一个参数。
关于如何做到这一点,有什么想法吗?
https://stackoverflow.com/questions/51865386
复制相似问题