javascript 将值从指令传递给控制器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31069816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing values from directive to controller
提问by Thomas Weglinski
Below is my html template:
下面是我的 html 模板:
<div ng-app="dr" ng-controller="testCtrl">
<test color1="color1" data-method="ctrlFn(msg)"></test>
</div>
Below is my code:
下面是我的代码:
var app = angular.module('dr', []);
app.controller("testCtrl", function($scope) {
$scope.ctrlFn = function(arg) {
alert(arg);
}
});
app.directive('test', function() {
return {
restrict: 'E',
scope: {
fromDirectiveFn: '&method'
},
link: function(scope, elm, attrs) {
//Way One
scope.hello = "some message";
scope.fromDirectiveFn(scope.hello);
}
}
});
<div ng-app="dr" ng-controller="testCtrl">
<test color1="color1" data-method="ctrlFn(msg)"></test>
</div>
Why am i getting "undefined" instead of "some message"
为什么我收到“ undefined”而不是“ some message”
Below is a fiddle http://jsfiddle.net/j2K7N/27/
下面是一个小提琴 http://jsfiddle.net/j2K7N/27/
回答by Thomas Weglinski
Your code is almost correct, however you had several issues here:
您的代码几乎是正确的,但是您在这里遇到了几个问题:
<test color1="color1" data-method="ctrlFn(msg)"></test>
Here you pass the ctrlFn()
function from your controller, which takes one undefined argument msg
, that causes the alert message with "undefined" text. I suggest to modify the HTML code to this:
在这里,您ctrlFn()
从控制器传递函数,该函数采用一个未定义的参数msg
,这会导致带有“未定义”文本的警报消息。我建议将 HTML 代码修改为:
<test color1="color1" data-method="ctrlFn"></test>
Note that I pass the ctrlFn
as a variable, not function.
请注意,我将 传递ctrlFn
为变量,而不是函数。
In your directive code, I changed the scope binding to =
to make sure that the ctrlFn
will point to your controller function. This also sets up a two-way binding between the directive's scope and the controller (parent) scope. Then the whole JS code of the directive will look like this:
在您的指令代码中,我将范围绑定更改为=
以确保ctrlFn
将指向您的控制器函数。这也在指令的范围和控制器(父)范围之间建立了双向绑定。那么指令的整个 JS 代码将如下所示:
app.directive('test', function() {
return {
restrict: 'E',
scope: {
fromDirectiveFn: '=method'
},
link: function(scope, elm, attrs) {
//Way One
scope.hello = "some message";
scope.fromDirectiveFn(scope.hello);
}
}
});
Just replacing the &
to =
. Working fork: http://jsfiddle.net/L8masomq/
只需替换&
to =
。工作叉:http: //jsfiddle.net/L8masomq/
回答by harishr
回答by user3030505
Actually, the code is correct. But, the value of msg which is getting undefined. Thus, you ctrlFn(msg) is returning as undefined. adding the 'msg' property and assigning the scope.hello will resolve the problem. Check the improved [Jsfiddle][1] here.
实际上,代码是正确的。但是, msg 的值变得未定义。因此,您 ctrlFn(msg) 返回未定义。添加 'msg' 属性并分配 scope.hello 将解决该问题。在此处查看改进的 [Jsfiddle][1]。
scope.fromDirectiveFn({'msg': scope.hello});