Angular scope from directive template function

I have a directive that has a function for a template

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) {

Is it possible to access the directive area from a template function? I'm trying to do something like

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

because I want to display a different template based on different values

+4
source share
1 answer

You can access the $ scope directive from the Link function, $ compile any HTML and add it to the directive element (which could actually be initialized as empty):

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

Note that I must explicitly specify the data model for the tag (ng-model = "scope"). I could not get it to work differently.

+6
source

All Articles