访问角度指令模板中的隔离范围

时间:2016-01-11 20:24:11

标签: angularjs angularjs-scope angular-directive

我目前正在编写一个角度指令,该指令在不同的HTML文件和隔离模板中使用模板。该指令通过@获取一些字符串到其作用域,该值在控制器函数中可用。 不知何故,它不能通过HTML模板中的{{}}获得。为什么会这样?我怎么能改变呢?我使用父作用域阅读了有关模板的内容,但我并不完全理解。

这是一个代码示例:

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
       }
    }
});

模板的html代码:

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

浏览器中的结果完全相同:

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

感谢您的帮助!

PS这是一个jsfiddle:fiddle

1 个答案:

答案 0 :(得分:3)

您的小提琴不正确,因为您没有定义控制器或正确注入$ scope。以下内容可以正常使用:

模板:

<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

请注意,在我的示例中,出于一致性原因,指令控制器中的注入变量应为$scope,而不是scope

相关问题