我可以在模板功能中使用指令吗?

时间:2016-12-06 19:13:19

标签: angularjs templates angularjs-directive

所以这是一个我刚刚为这个问题写的简单例子,我很好奇我是否能够使用一个指令并将一个对象传递给指令的属性,所有这些都在模板中, not templateUrl 。我认为它会起到这样的作用:

angular.module('myModule')
  .directive('someDirective', function() {
    return {
      scope: {
        u: '=',
      },
      template: '<avatar user="u"></avatar>',
    };
  });

2 个答案:

答案 0 :(得分:0)

是的,你可以!而且定义顺序并不重要。

app.directive("directive1", function() {
    return {
        restrict: 'E',
        scope: {
            u: '@'
        },
        template : "<h4>{{u}}</h4><directive2 user='{{u}}'></directive2>"
    };
});
app.directive("directive2", function() {
    return {
        restrict: 'E',
        scope: {
            user: '@'
        },
        template : "<h1>{{user}}</h1>"
    };
});

在此jsfiddle

中查看此操作

答案 1 :(得分:0)

是的,通过范围属性传递您的状态很容易。这是一个展示这个概念的plunkr

app = angular.module('app',[])
  .directive('someDirective', function() {
    return {
      scope: {
        u: '=',
      },
      template: '<avatar user="u"></avatar>',
    };
  }).directive('avatar', function() {
    return {
      scope: {
        user: '=',
      },
      template: '<span>{{user.name}}</span>',
    };
  })