【问题标题】:Angular Expressions Missing in Dynamically Generated Template动态生成的模板中缺少角表达式
【发布时间】:2014-04-21 20:37:51
【问题描述】:

我遇到了动态生成指令(使用函数)和角度表达式在屏幕上最终标记中被过滤掉的问题。我创建了一个JSFiddle displaying the problem here

我正在动态生成模板,因为我们需要一种基于元素内部属性生成标记的方法。

基本上在定义这样的表达式时:

angular.module('ui.directives', []).directive('uiBar', function() {
    return {
        restrict: 'E',
        template: function(element, attrs) {
            console.log('hello');
            return '<div>lol: {{ user }}</div>';
        }
    };
});

然后像这样将它放入体内:

<div ng-app="myApp">
    <ui-bar>I should change to iambar</ui-bar>
</div>

生成的标记是:

<div ng-app="myApp" class="ng-scope">
    <ui-bar><div class="ng-binding">lol: </div></ui-bar>
</div>

表达式由于某种原因被删除。有人经历过吗?

【问题讨论】:

  • 是否需要在视图中显示表达式{{ user }}?如果没有,您可以在指令(或其父范围)中定义user,它将被显示。如果在作用域(或父作用域)中找不到名称,则 Angular 会默默地将表达式编译为无值。看看这个小提琴。 jsfiddle.net/qQPb6
  • 这是另一个示例,表明它确实在工作:jsfiddle.net/EM9wv/7 发生的情况是 angularjs 编译了您使用 {{ user }} 指定的 ng-bind 指令
  • 也许 Transclude 可以满足您的需求?链接:docs.angularjs.org/api/ng/directive/ngTransclude

标签: javascript angularjs angularjs-directive


【解决方案1】:

我不太明白您要使用动态生成的模板来完成什么。以下是我通常会做的解决您的示例的方法。

HTML 看起来像这样。

<ui-bar new-value="hello">I should change</ui-bar>

指令的返回语句看起来像这样

return {
  restrict: 'E',
  template: "<div>lol: {{ user }}</div>",

  link: function (scope, element, attrs){
    scope.user = attrs.newValue;
  } // end link
} // end return

上面的代码可以在你的 jsFiddle 中运行。

如果您可以添加更多信息,我们可能会提供更多示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    • 1970-01-01
    • 2019-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多