如何通过一个JSON作为字符串参数来指令 [英] how to pass a json as a string param to a directive
问题描述
当我尝试EVAL下面的JSON形式,它给了我一个错误 -
When I try to eval the below json form it gives me an error -
eval("{form: 'form' , nameToMatch: 'password1'}")
为什么上面的表格无效?
Why is the above form not valid ?
但下面的工作正常 -
However the below works fine -
eval("{form: 'form'}")
我想通过上面的JSON作为一个字符串,作为参数输入到指令中。
I am trying to pass the above json as a string, as a param input to a directive.
下面是HTML -
Below is the html -
<input type="password" name="password2" ng-model="user.confirmPassword" placeholder="Confirm Password" match="{form: 'form', nameToMatch: 'password1'}" required="required"/>
谢谢,
穆尔塔扎
Thanks, Murtaza
推荐答案
把括号围绕你的JSON:
Put parens around your json:
eval("({form: 'form' , nameToMatch: 'password1'})")
似乎并不喜欢的角度的问题,但。不知道你想做什么:
Doesn't seem like an angular question though. Not sure what you're trying to do:
总之,要的通过的JSON的到有很多方法可以做到这一点的指令。我不知道为什么你要做到这一点,不只是传递一个对象,但。
Anyhow, to pass the json to the directive there are lots of ways to do that. I'm not sure why you'd want to do that and not just pass an object though.
通过JSON可以做了很多办法...
passing json can be done a lot of ways...
-
从你的属性对象:
From your attributes object:
app.directive('foo', function () {
return function(scope, element, attrs) {
var obj = eval('(' + attrs.foo + ')');
};
});
其中,
<div foo="{'test':'wee'}"></div>
这是一个孤立的范围:
From an isolated scope:
app.directive('foo', function () {
return {
restrict: 'E',
scope: {
'jsonIn' : '@'
},
link: function(scope, element, attrs) {
var obj = eval('(' + scope.jsonIn + ')');
};
};
});
其中,
<foo json-in="{'test':'wee'}"></foo>
但它是迄今为止最好避免使用本机评估
不惜一切代价,如果你能。这在几乎所有你能情况。如果你有一些数据只是把它放在一个对象的范围的参数,并在无论是通过在一个偏僻的范围双向财产,或者通过名称传递它,做它的角$ EVAL。
But it's by far better to avoid using the native eval
at all costs, if you can. Which in almost all cases you can. If you have some data just put it in an object on a scoped parameter and pass it in either via a two-way property on an isolated scope, or by name and do an angular $eval on it.
编辑:在... ...的传递对象
您可以使用两种方式在一个偏僻的范围绑定:
You could use two way binding on an isolated scope:
app.directive('foo', function (){
return {
restrict: 'E',
scope: {
'data' : '='
},
link: function(scope, elem, attrs) {
console.log(scope.data);
}
};
});
其中,
<foo data="{ test: 'wee' }"></foo>
关于做这种方式很酷的事情,就是如果你使用一个范围的属性,它会更新双向:
The really cool thing about doing it this way, is if you're using a scoped property it will update bi-directionally:
app.controller('MainCtrl', function($scope) {
$scope.bar = { id: 123, name: 'Bob' };
});
其中,
<foo data="bar"></foo>
我希望帮助。
这篇关于如何通过一个JSON作为字符串参数来指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!