gpt4 book ai didi

javascript - AngularJS - 在指令回调中包含变量

转载 作者:行者123 更新时间:2023-11-28 06:43:38 24 4
gpt4 key购买 nike

我试图让我的指令将参数传递给调用者,但我无法让它工作。

注意:我可以调用不带参数的函数。但是一旦我添加参数,它就会中断:

这是骗子:( http://embed.plnkr.co/autsgiBlWjz8cX2BL6Sj/preview )

代码如下,供您引用:

//代码放在这里 Angular .module('myApp', []);

angular
.module('myApp')
.directive('myDirective', myDirective)
.controller('ParentController', ParentController);

function myDirective() {
return {
restrict: 'E',
controller: {},
controllerAs: 'vm',
bindToController: {
myCallback: '&'
},
scope: {},
template: '<div><button data-ng-click="myCallback({msg:123})Call Callback</button></div>'
};
}

function ParentController() {
var self = this;

self.parentCallback = parentCallback;

function parentCallback(args) {
alert('The message is: ' + args.msg);
}
}

此处的 HTML 代码:

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

<body>
<div data-ng-app="myApp" data-ng-controller="ParentController as ctrl">
<my-directive my-callback="ctrl.parentCallback(args)"></my-directive>
</div>
</body>

</html>

最佳答案

来自angular doc

Often it's desirable to pass data from the isolate scope via an expression to the parent scope, this can be done by passing a map of local variable names and values into the expression wrapper fn. For example, the hideDialog function takes a message to display when the dialog is hidden. This is specified in the directive by calling close({message: 'closing for now'}). Then the local variable message will be available within the on-close expression.

如果您想收到args这样,<my-directive>的模板应如下所示。

<div><button data-ng-click="myCallback({args: {msg:123}})">Call Callback</button></div>

关于javascript - AngularJS - 在指令回调中包含变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33583712/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com