2
votes

I am currently writing an angular directive that uses a template in a different HTML file and an isolated template. The directive gets some string via @ to its scope and that value is available in teh controller function. Somehow its not available via {{}} in the HTML template. Why is that so? How can I change that? I read something about the template using the parent scope but I don't fully understand that.

Here is a code example:

angular.module('moduleName')

.directive('aGreatDirective', function () {
    return {
        restrict: 'E',
        scope: {
            mapid: '@'
        }, 
        templateUrl: "path/to/template.html",

        controller: ['$scope', function (scope) {
            console.log($scope.mapid); // is defined
       }
    }
});

And the html code for the template:

<div id="{{mapid}}"></div>

The result in the browser is exactly the same where it should be:

<div id="theValueOfmapid"></div>

Thanks for your help!

PS Here is a jsfiddle: fiddle

1
Can you add a jsfiddle?Adam Axtmann
I just did. {{mapid}} should be thisisthemapid in the output, but it isn't. The console statements are also strange. In my console I see the mapid attribute, but $scope.mapid is undefined...CodeO

1 Answers

3
votes

Your fiddle was incorrect since you didn't have your controller defined or $scope injected properly. The following will work just fine:

template:

<div ng-controller="MyCtrl">
    <a-great-directive mapid="thisisthemapid"></a-great-directive>
    Some other code
</div>

js:

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

myApp.controller('MyCtrl', function () {
});

myApp.directive('aGreatDirective', function() {
    return {
        restrict: 'E',
        scope: {
            mapid: '@'
        },
        template: "<div id='{{mapid}}'> {{mapid}} </div>",
        controller: ['$scope', function($scope) {
            console.log($scope.mapid); // is defined
        }
    ]}
});

Fiddle

Note that in my example, the injected variable in your directive's controller should be $scope, not scope, for consistency reasons.