如何将angularjs变量值传递给javascript函数? [英] How to pass an angularjs variable value to a javascript function?
问题描述
在此code我试图传递一个AngularJS参数设置为一个函数:
In this code I'm attempting to pass a AngularJS paramter to a function :
<div ng-app ng-controller="LoginController">
<p><a href='javascript:display({{ user.firstName }});'>{{ user.firstName }}</a>
</div>
function LoginController($scope) {
$scope.user = {
firstName: "Foo"
};
}
function display(text){
alert(text)
}
在富是点击富应该被显示,但如何将angularjs变量值传递给javascript函数?
When "Foo" is clicked "Foo" should be displayed but how to pass an angularjs variable value to a javascript function ?
小提琴: http://jsfiddle.net/Lt7aP/534/
推荐答案
的问题是该值,富
,被写入了为$ C的一部分$ C。在这种情况下,出现的是一个不存在的变量
The issue is that the value, "Foo"
, is being written out as part of code. In this case, appearing to be a variable that doesn't exist.
display(Foo) // ReferenceError: Foo is not defined
这将需要至少被引用,被理解为一个字符串值。
It'll need to at least be quoted to be understood as a string value.
display('Foo')
您可以使用 JSON
过滤器要做到这一点,包括任何必要的转义序列。
You can use the json
filter to do this to include any necessary escape sequences.
<a href='javascript:display({{ user.firstName|json }});'>{{ user.firstName }}</a>
或者,如果你附加功能到 $范围
,你可以参考它,没有价值{{...}}
或在 NG-点击
:
Or, if you attach the function to the $scope
, you can reference it and the value without {{...}}
or filters in an ng-click
:
function LoginController($scope) {
$scope.user = {
firstName: "Foo"
};
$scope.display = function (text) {
alert(text);
};
// or keep the global function and reference it on the $scope
// $scope.display = display;
}
<a ng-click="display(user.firstName)">{{user.firstName}}</a>
这篇关于如何将angularjs变量值传递给javascript函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!