Javascript 指令模板函数的角度访问范围

Javascript 指令模板函数的角度访问范围,javascript,angularjs,Javascript,Angularjs,我有一个指令,它有一个模板函数 restrict: 'E', // 'A' is the default, so you could remove this line scope: { field : '@field', }, template: function( element, attrs) { //some code here }, link: function (scope, element, attrs)

我有一个指令,它有一个模板函数

restrict: 'E',   // 'A' is the default, so you could remove this line
    scope: {
        field : '@field',

    },
    template: function( element, attrs) {
         //some code here
    },
    link: function (scope, element, attrs) {
是否可以从模板函数访问指令的范围?我正试着做类似的事情

if (scope.columnType == 'test'){ .. }

因为我想基于其他值呈现不同的模板,所以您可以从Link函数访问指令$scope,$compile any HTML并将其附加到指令元素(实际上,可能已初始化为空):

angular.module(“示例”)
.directive('example',function($compile){
返回{
限制:'E',
链接:函数(范围、元素、属性){
scope.nums=[1,2,3];
var html='

{{{n}

'; var el=$compile(html)(范围); 元素。追加(el); } } });

请注意,我必须明确指定标记的数据模型(ng model=“scope”)。否则我无法让它工作。

不,这是不可能的;指令的作用域最早可用的地方是pre-link函数或控制器。在该模板中,您要做的是..我们可能会转移到不同的方法我正在尝试根据我预先计算的内容显示不同的dom元素。请看一下。。这和你想要的一样谢谢,这很有帮助。
angular.module("example")
.directive('example', function($compile) {
    return {
        restrict: 'E',
        link: function(scope, element, attrs){
            scope.nums = [1, 2, 3];
            var html = '<div ng-model="scope"><p ng-repeat="n in nums">{{ n }}</p></div>';
            var el = $compile(html)(scope);
            element.append(el);
        }
    }
});