Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular access scope from directive template function

I have a directive which has a function for 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's scope from the template function? I'm trying to do something like

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

because I want to render a different template based on other values

like image 628
LucianRadu Avatar asked Jun 08 '15 08:06

LucianRadu


1 Answers

You can access the directive $scope from the Link function, $compile any HTML and append it to the directive element (that in fact, could have being 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);
        }
    }
});

Notice that I had to explicitly specify the data model for the tag (ng-model = "scope"). I couldn't make it work otherwise.

like image 168
Patricio Córdova Avatar answered Nov 13 '22 12:11

Patricio Córdova