Change attribute of custom directive

核能气质少年 提交于 2019-12-11 02:52:54

问题


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>

回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/32409957/change-attribute-of-custom-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!