简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM