角度指令范围值

时间:2016-09-28 06:09:48

标签: javascript angularjs angularjs-directive angularjs-scope

  <tab page="book"> </tab>
  <tab page="dial"> </tab>
  <tab page="groupe"> </tab>
  <tab page="log"> </tab>
  <tab page="star"> </tab>

正如您所看到的,我有一个名为标签的指令,而此标签的属性页面

我需要根据页面属性

的值更改 templateUrl
  

如果页面值为page="abc",则 templateUrl 应为templateUrl: 'tab/abc.html',

这是我的指令代码

contactBook.directive('tab', function() {
    let m = 'tab/default.html';
    return {
        restrict: 'E',
        scope: {
            page: '@',
        },
        templateUrl: m,
        link: function(scope, element, attributes) {
            m = "tab/" + scope.page + ".html";      
        },
    };
});

这在逻辑上是可能的吗?或任何替代方法来做到这一点..?

2 个答案:

答案 0 :(得分:7)

templateUrl: function(elem,attrs) {
    return "tab/" + attrs.page + ".html" || 'tab/default.html';
},

答案 1 :(得分:2)

contactBook.directive('tab', function() {
    let m = 'tab/default.html';
    return {
        restrict: 'E',
        scope: {
            page: '@',
        },
        templateUrl: m,
        link: function(element, attributes) {
            m = "tab/" + attributes.page + ".html";    // attributes.page can access attribute value
        },
    };
});

您正在隔离tab指令的范围,并且您有一个绑定

 scope: {
          page: '@',
     }

如果你只是将父范围的string传递给指令,那么使用

<tab page={{book}}> </tab>

但是如果你想将一个对象从父范围传递给指令那么

<tab page="book"> </tab>

然后在你的指令

  scope: {
              page: '=',
         }
相关问题