How to use a scope in Directive template

本秂侑毒 提交于 2019-12-13 17:05:57

问题


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

回答1:


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

}]);

you can check it out here




回答2:


The scope option within directives provides an isolated scope to remove the scope issues from parent controller and provides the directive to be portable and decoupled with the controller. In your scenario you can define your isolated scope for template as below:

JS Code:

directive("data", ['$compile', '$http', '$templateCache',function ($http,$rootScope) {
 return{
    restrict: 'EA',
    scope: {
      template: '='
    }
    template:function(element , attrs){ 
        return scope.template;
    }
}

HTML:

<data template='something'></data>

This way of isolated scope provides the binding strategies ('@', '=') for one way or two-way data binding of scope variables to DOM. In your case template attribute in data element will be two-way data bound to scope variable template.



来源:https://stackoverflow.com/questions/25341641/how-to-use-a-scope-in-directive-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!