0

I have an object attribute defined in an element directive, which itself is defined inside an ng-repeat directive:

<div ng-repeat="element in array">
    <my-directive el-sel="{{element}}>
        <something else>
    </my-directive>
</div>

And this is myDirective:

app.directive('myDirective', function() {
  return {
    restrict: 'E',
    scope: false,
    link: function($scope, $element, $attrs) {

        console.log('element:' + JSON.stringify($attrs.elSel));
          console.log('href: ' + $attrs.elSel.href);

    }
  }
});

The console results are:

element:"{\"name\":\"a name\",\"href\":\"#something\"}"
href: undefined

What is the explanation for this behavior, and what am I doing wrong?

1
  • Did you try parsing console.log($attrs.elSel); simply to check the data, whether that object is coming up as a string or in some other data type. Commented Nov 1, 2017 at 16:26

1 Answer 1

1

You're passing {{element}} as a string. This is what {{variable}} does.

In the short term, this will fix it:

console.log('href: ' + JSON.parse($attrs.elSel).href);

Here's a minimal example of passing an object to a directive:

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
  $scope.something = {
    name: 'a name',
    href: '#somewhere'
  };
});

app.directive('myDirective', function() {
  return {
    restrict: 'E',
    scope: {
      elSel: '='
    },
    link: function($scope, $element, $attrs) {
      console.log($scope.elSel)
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="MainCtrl">
  <my-directive el-sel="something">
  </my-directive>
</div>

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

2 Comments

Thank you, I'll accept your answer as soon as SO let me, one more question though, is there a way to pass the object from the ng-repeat as a reference? Because without the braces it doesn't
Have edited my answer with an example for you. Further reading here.

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.