如何在指令模板中使用范围 [英] How to use a scope in Directive template

查看:28
本文介绍了如何在指令模板中使用范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在这样的指令的模板函数中使用 $scope 变量.换句话说,我想在指令内部并使用 $scope 变量生成指令模板.

I want to use $scope variable in template function of directive like this. In the other words i want to generate directive template inside of directive and by using $scope variable.

帮助我将模板函数连接到控制器.

Help me to connect template function to controller.

directive("data", ['$compile', '$http', '$templateCache',function ($http,$rootScope) {
    return{
    link: function (scope, elem, attrs, ctrl) {
        scope.template = something // I want Generate template here
    },
    template:function(element , attrs){ 
        return $scope.template // I can't access scope here
    }
}

推荐答案

你不能访问模板函数中的作用域,如果你想以某种方式生成模板然后在指令中渲染模板我会建议以这种方式在链接函数中使用 $compile service :

You can not access to the scope in the template function, if you want to generate the template somehow and then render the template inside the directive I'll suggest to use the $compile service inside the link function in this way :

var a = angular.module('myApp', []);

a.controller('ctrl', function ($scope) {
    $scope.myTemplate = '<span class="custom-tpl"> my template </span>';
});

a.directive('dynamicTemplate', [ '$compile',

function ($compile) {
    'use strict';
    return {
        restrict: 'A',
        scope: {
            customTemplate: '='
        },
        link: function ($scope, $element, $attrs, $controller) {
            var compiledTemplate = $compile($scope.customTemplate)($scope);
            $element.html('').append(compiledTemplate);
        }
    };

}]);

您可以在这里查看

这篇关于如何在指令模板中使用范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆