user93 user93 - 3 months ago 78
AngularJS Question

How to pass json object in one way binding to directive angularjs

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

Answer

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="angularjs@1.5.8" 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

Comments