Change attribute of custom directive

2019-07-10 17:11发布

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>

2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-07-10 17:30

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

查看更多
贪生不怕死
3楼-- · 2019-07-10 17:32

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

查看更多
登录 后发表回答