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

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

本文介绍了访问角度指令模板中的隔离范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在编写一个角度指令,该指令在另一个HTML文件中使用一个模板,并在一个隔离的模板中使用.指令通过@到达其作用域的字符串,并且该值在控制器函数中可用.不知何故,它无法通过HTML模板中的{{}}使用.为什么?我该如何改变呢?我使用父范围阅读了有关模板的内容,但我对此并不完全理解.

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.

这是一个代码示例:

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代码:

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>

感谢您的帮助!

PS这是一个jsfiddle: fiddle

PS Here is a jsfiddle: fiddle

推荐答案

您的小提琴不正确,因为您没有定义控制器或正确注入了$ scope.以下将正常工作:

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

模板:

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

小提琴

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

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

这篇关于访问角度指令模板中的隔离范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 02:03