4

I'm having a bit of trouble understanding how attribute values work in AngularJS directives. No matter what I try, literal attribute values come out as undefined when I try to use them within the directive controller.

Say in my HTML I envoke a directive like this:

<div ng-controller="MyCtrl">
    <my-directive reference-attr='referenceVal' literal-attr='literalVal'></my-directive>
</div>

referenceVal and literalVal are both defined in my controller, like this:

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

function MyCtrl($scope) {
    $scope.referenceVal = 'This was passed by reference';
    $scope.literalVal = 'This was also passed by reference, but should have been literal';
}

And I try to pick them up in my directive:

myApp.directive("myDirective", function () {

    return {
        restrict: "E",
        replace: true,
        scope: {
            referenceAttr: "=",
            literalAttr: "@"
        },
        template: '<div><p>Reference:{{referenceAttr}}</p><p>Literal:{{literalAttr}}</p></div>',
        controller: function ($scope) {
            alert("ref: " + $scope.referenceAttr + ", lit: " + $scope.literalAttr);
        }
    };
});

The output looks fine:

Reference: This was passed by reference
Literal: literalVal

But the alert message is crap:

ref: This was passed by reference, lit: undefined

You can try it out yourself with this JSFiddle

Any idea why literalAttr is undefined in the directive scope at this point?

2
  • Ancient Angular versions, like 1.0.1 used in the Fiddle had some problems (?) with interpolated directive attributes. Recent versions exhibit the expected behaviour. See forked fiddle Commented Jan 30, 2014 at 8:28
  • Ah, thanks Nikos, a newer version of Angular JS fixes it (d'oh). Do you want to make this an answer and I'll accept it? Commented Jan 30, 2014 at 23:58

1 Answer 1

3

This is a problem with the oldest versions of Angular, e.g. the 1.0.1 used in the fiddle. Recent versions exhibit the expected behaviour.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.