7

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

4
  • 3
    No, it is not possible; the earliest place where the directive's scope is available is the pre-link function or the controller. Commented Jun 8, 2015 at 8:52
  • what you are going to do that in that template..we might can move to different approach Commented Jun 8, 2015 at 9:07
  • 1
    I'm trying to display different dom elements based on something that I pre compute. Commented Jun 8, 2015 at 9:08
  • take a look at this.. it is the same as you want here stackoverflow.com/a/30672887/2435473 Commented Jun 8, 2015 at 9:17

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.