javascript - AngularJS 自定义指令显示 {{obj}} 但不显示 {{obj.prop}}?

标签 javascript angularjs angularjs-directive directive

我正在尝试构建一个非常简单的 Angular 指令:

app.directive("myDirective", function () {
    return {
        template: "{{result}} {{result.startTime}}",
        scope: {
            result: '@result'
        }
    };
});

我在 View 中这样使用它:

<div my-directive result="{{result}}"></div>

问题是 {{result}} 正确显示(作为 json)abject,而 {{result.startTime}} 未显示,尽管事实上,显示的 {{result}} 包含 startTime 属性。

最佳答案

2个问题:

1 您需要传入模型,而不是内插的字符串。

<div my-directive result="result"></div>

2 您需要将值分配给指令,因此请使用“=”而不是“@”,这将为您提供从指令到仅 DOM 的单向绑定(bind)。

app.directive("myDirective", function () {
    return {
        template: "{{result}}, {{result.startTime}}",
        scope: {
            result: '='
        }
    };
});

Working Demo

关于javascript - AngularJS 自定义指令显示 {{obj}} 但不显示 {{obj.prop}}?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18597158/

相关文章:

javascript - 简单的移动 jQuery 切换按钮和 .toggle 最新 jQuery 的替代品

javascript - JSON 中第 40 位的意外标记 t

javascript - 如何解决另一个 promise 中的 promise 并在 Controller 中获得解决方案?

javascript - 在输入不匹配时添加 ng-invalid 类

javascript - javascript中这些变量有什么区别

javascript - Vue.js axios 从本地存储(localforage)获取值返回promise对象而不是值

javascript - 如何以编程方式选择一个选项作为所选选项?

angularjs - 如何使用 `$destroy` 指令并替换为新值

javascript - 将 ng-model 属性传递给自定义指令

Javascript onclick 附件索引器问题