【发布时间】:2017-06-29 06:31:02
【问题描述】:
我正在尝试将参数传递给一个函数,在一个指令链接函数内部,类似于这个问题: Angular: calling controller function inside a directive link function using &
但是,虽然我已经看到了一些示例,例如:Passing Parameters from a Directive to a function,但我已经看到在指令内的链接中设置了参数值。但是,我还没有看到您在哪里传递原语,例如将数字作为参数传递给将其传递给控制器函数的指令。
我尝试了多种方法,但还没有弄清楚语法。
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(count)"></my-directive>
</div>
</div>
</body>
</html>
SCRIPT.JS
var app = angular.module('app', []);
app.controller("mainCtrl", function($scope) {
$scope.count = 0;
$scope.ctrlFn = function() {
$scope.count = 0;
console.log('In mainCtrl ctrlFn!');
$scope.count += count;
// console.log("count is: " + JSON.stringify($scope.count));
//Call service here
};
})
.directive('myDirective', function() {
return {
restrict: 'E',
scope: {
'count' : '&',
'ctrlFn' : '&'
},
template: "<div><button ng-click='ctrlFn({count: 10})'>Click Here</button></div>",
link: function(scope, element, attributes) {
var count = null;
scope.ctrlFn = scope.ctrlFn({count: count});
//scope.text = scope.fn({ count: 0 });
}
};
});
我的小伙伴在这里:http://plnkr.co/edit/6uDntNeqe0g343PmeCED?p=preview
在这个用例中可以将原语作为参数传入吗?如果是这样,我在这里错过了什么?
后果:
如果有人在 angularjs 文档中寻找这种语法:ctrlFn({count: 10}),这里会在自定义指令下提到它:
通常希望通过一个 表达式到父范围,这可以通过传递一个映射来完成 将局部变量名称和值放入表达式包装函数中。 例如, hideDialog 函数在何时显示一条消息 对话框被隐藏。这是通过调用在指令中指定的 关闭({消息:'暂时关闭'})。然后局部变量消息 将在关闭表达式中可用。
【问题讨论】:
标签: angularjs angularjs-directive custom-directive