How to use a scope in Directive template

2019-07-24 08:32发布

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

2条回答
家丑人穷心不美
2楼-- · 2019-07-24 08:55

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

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-07-24 08:57

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.

查看更多
登录 后发表回答