Access isolated scope in angular directive template

家住魔仙堡 提交于 2019-12-24 00:43: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.



来源:https://stackoverflow.com/questions/34730412/access-isolated-scope-in-angular-directive-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!