-->

Access isolated scope in angular directive templat

2019-07-14 05:09发布

问题:

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:

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.