angularjs - 如何在指令模板中使用范围

标签 angularjs angularjs-directive angularjs-scope

我想在指令的模板函数中使用 $scope 变量,如下所示。 换句话说,我想在指令内部并使用 $scope 变量生成指令模板。

帮我将模板函数连接到 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在链接函数中以这种方式:

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

}]);

你可以看看here

关于angularjs - 如何在指令模板中使用范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25341641/

相关文章:

angularjs - 为什么我的事件处理程序总是落后一个按键,而 $timeout 如何解决这个问题?

AngularJS - 将相同的 Controller 附加到多个 html 元素

javascript - 经过 $filter() 后日期发生变化

javascript - Angular JS/IONIC 读取 JSON 文件

angularjs - 如何从指令访问子 ngModel?

javascript - AngularJs ng-if 用于显示或跳过元素

javascript - AngularJS $scope.push 不从 $http 数据响应更新 View

angularjs - 在服务中返回已解析的 $resource

javascript - 在指令定义中的其他指令内添加指令

angularjs - nvd3 图表开始在浏览器中被压扁