Typo
Typo

Reputation: 1910

Angular Directive Attribute - Object Property undefined

I have an object attribute defined in an element directive, which itself it's 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

Could someone please explain this behavior and what I'm doing wrong?

Upvotes: 0

Views: 45

Answers (1)

UncleDave
UncleDave

Reputation: 7188

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>

Upvotes: 1

Related Questions