Angularjs templateUrl 无法在 ng-repeat 中绑定属性

Angularjs templateUrl fails to bind attributes inside ng-repeat

我正在使用指令显示 html 个片段。

和指令中的 templateUrl, 能够将片段包含为 html 文件。

指令不起作用,如果我尝试调用 在内置的 ng-repeat 指令中 ({{snip}} 按原样传递,没有替代):

div ng-repeat="snip in ['snippet1.html','snippet2.html']">
  <my-template snippet="{{snip}}"></my-template>
</div>

作为参考,这里是指令:

app.directive("myTemplate", function() {
return {
    restrict: 'EA',
    replace: true,
    scope: { snippet: '@'},
    templateUrl: function(elem, attrs) {
      console.log('We try to load the following snippet:' + attrs.snippet);
      return attrs.snippet;
    }
  };
});

还有一个plunker demo.

非常感谢任何指点。 (指令在我的代码中更复杂, 我试图得到一个最小的例子,其中的问题是可重现的。)

看看这个link

http://plnkr.co/edit/TBmTXztOnYPYxV4qPyjD?p=preview

app.directive("myTemplate", function() {
  return {
    restrict: 'EA',
    replace: true,
    scope: { snippet: '=snippet'},
    link: function(scope, elem, attrs) {
      console.log('We try to load the following snippet:' + scope.snippet);
    },
    template: '<div ng-include="snippet"></div>'
  };
})

attrs templateUrl 的参数在指令执行期间不会被插入。您可以使用以下方式实现此目的

app.directive("myTemplate", function() {
  return {
    restrict: 'EA',
    replace: false,
    scope: { snippet: '@'},
    template: '<div ng-include="snippet"></div>'
  };
}); 

演示:http://plnkr.co/edit/2ofO6m45Apmq7kbYWJBG?p=preview

可以使用ng-include,看属性。像这样:

app.directive("myTemplate", function() {
    return {
        restrict: 'E',
        replace: true,
        link: function(scope, elem, attrs) {
            scope.content = attrs.snippet;
            attrs.$observe("snippet",function(v){
                scope.content = v;
            });
        },
        template: "<div data-ng-include='content'></div>"
    };
});

刚刚更改了指令结构。我们将使用指令本身来渲染它,而不是使用 ng-repeat 来渲染所有模板,因为我们将把整个模板数组传递给指令。

HTML

<div ng-init="snippets = ['snippet1.html','snippet2.html']">
    <my-template snippets="snippets"></my-template>
</div>

指令

angular.module('myApp', [])
.controller('test',function(){})
    .directive("myTemplate", function ($templateCache, $compile) {
    return {
        restrict: 'EA',
        replace: true,
        scope: {
            snippets: '='
        },
        link: function(scope, element, attrs){
            angular.forEach(scope.snippets, function(val, index){
                //creating new element inside angularjs
                element.append($compile($templateCache.get(val))(scope));
            });
        }
    };
});

Working Fiddle

希望对您有所帮助。谢谢

看来你是在试图根据某种逻辑有不同的看法 并且您使用了 templateUrl 函数,但 Angular 插值不起作用,以解决此问题

don't use templateUrl

那么如何在不使用 templateUrl 的情况下做到这一点

就是这样

app.directive("myTemplate", function() {
    return {
        link: function(scope, elem, attrs) {
           $scope.templateUrl = '/ActivityStream/activity-' + $scope.ativity.type + '.html'
        },
        template: "<div data-ng-include='templateUrl'></div>"
    };
});

希望这简单易懂