balaji g
balaji g

Reputation: 153

Change attribute of custom directive

I have custom directive to load pages inside a div

.directive('page', function () {
    return {
        templateUrl: function (elem, attr) {
            return 'pages/page-' + attr.num + '.html';
        }
    };
});

here is the dom representation of the custom directive

<div page num="{{pageNo}}"></div>

Here i want to change the page number from the controller.

Directive works fine if the value added directly

<div page num="1"></div>

Upvotes: 2

Views: 207

Answers (2)

Pankaj Parkar
Pankaj Parkar

Reputation: 136184

As you want the interpolated value of pageNo inside your directive, You cant get that value inside the templateUrl function. You need to use ng-include directive to get the value of scope name inside your directive.

Markup

<div page num="{{pageNo}}"></div>

Code

app.directive('page', function() {
  return {
    scope: {
      num: '@'
    },
    template: '<div ng-include="\'pages/page-\'+ num + \'.html\'"></div>'
  };
});

Working Plunkr

Upvotes: 3

lex82
lex82

Reputation: 11317

From the docs:

You do not currently have the ability to access scope variables from the templateUrl function, since the template is requested before the scope is initialized.

This means you only have access to the literal value of the attribute and you cannot evaluate it against a certain scope. You might be able to define your directive inside a closure and access the parent scope this way. Then you could call scope.$eval('pageNo').

However: This would be a really ugly hack. I'd rather choose the solution with ng-include suggested by @pankaj-parkar

Upvotes: 1

Related Questions