2

I need to pass object to angularjs directive but I cannot use & or = for binding. I tried converting string to object using | json filter and creating temporary variable. still conversion does not work how do i proceed. Thanks in advance

1
  • It's not clear what you are trying to accomplish here. Why can you not use & or =? And what does "conversion does not work" mean? Commented Sep 1, 2016 at 16:24

1 Answer 1

2

To pass an object with @ you have to use {{}} (mustache) and on directive side it does get it as an object and you can use it like this:

<!DOCTYPE html>
<html>

  <head>
    <script data-require="[email protected]" data-semver="1.5.8" src="https://opensource.keycdn.com/angularjs/1.5.8/angular.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script >
      var app = angular.module('yourApp', []);
      app.controller('FooCtrl', function($scope) {
        $scope.obj = {
          foo: 'bar',
          bar: 'foo'
        };
      });
      app.directive('directiveName', function(){
        return {
            restrict:'E',
            scope: {
               parameter: '@'
            },
            template:'<div>parameter: {{parameter}} foo: {{obj.foo}} bar: {{obj.bar}}</div>',
            controller: function($scope) {
              $scope.obj = JSON.parse($scope.parameter);
            }
          };
        });

    </script>
  </head>

  <body ng-app="yourApp">
    <div ng-controller="FooCtrl">
        <directive-name parameter="{{obj}}"></directive-name>
    </div>
  </body>

</html>

I did create a plunker

Sign up to request clarification or add additional context in comments.

1 Comment

I tried it but it passes it as string but how do I get object inside directive

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.