Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

angularjs - how to pass a json as a string param to a directive

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'}")

I am trying to pass the above json as a string, as a param input to a directive.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

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.

passing json can be done a lot of ways...

  1. From your attributes object:

    app.directive('foo', function () {
       return function(scope, element, attrs) {
           var obj = eval('(' + attrs.foo + ')');
       };
    });
    

    where

    <div foo="{'test':'wee'}"></div>
    
  2. From an isolated scope:

    app.directive('foo', function () {
       return {
         restrict: 'E',
         scope: {
          'jsonIn' : '@'
         },
         link: function(scope, element, attrs) {
           var obj = eval('(' + scope.jsonIn + ')');
         };
       };
    });
    

    where

    <foo json-in="{'test':'wee'}"></foo>
    

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.

EDIT: The pass an object in...

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);
     }
  };
});

where

<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' };
});

where

<foo data="bar"></foo>

I hope that helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...