javascript - 向 AngularJS 中的指令提供远程数据

标签 javascript ajax angularjs angularjs-directive angularjs-scope

在开发指令时,最好的做法是将数据/模型与实际指令分开。

例如,如果我有一个名为“Event”的指令,例如

<div class="event">
    <h1>{event.title}</h1>
    <small>{event.startDate}</small>
</div>

以最可重用的模式向指令提供数据的最佳方式是什么?通过服务?

最佳答案

指令可以做很多事情。您可以通过多种方式处理数据。更直接的方法是将数据或引用传递到您的指令中。查看下面的链接以供引用。作为您的代码的示例,我将执行以下操作:

<div dir-event event-title="context.title" event-start="context.startDate" ></div>

在 HTML 中,context.title 和 context.startDate 是 Controller 上的对象。然后对于指令:

App.directive("dirEvent", function() {
    return{
        restrict: "A",
        scope:{
            title:"=",
            startDate:"="
        },
        transclude: true,
        template: "<div class='event'><h1>{{title}}</h1><small>{{startDate}}</small></div>",
        replace: true
    }
});

Directives

关于javascript - 向 AngularJS 中的指令提供远程数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17823443/

相关文章:

javascript - AngularJs $watch 抛出无法读取 null 的属性 'replaceChild'

javascript - 是否有任何脚本可以停止显示 ALT ="text"作为 IE 6 和 7 中的工具提示?

jquery - 使用 jQuery getJSON 时 JSON Feed 返回 null

javascript - 如何在 SQL Server 2012 中使用 Soap Jquery 保存数据?

javascript - 如果实例化类,PHP 不会向 ajax 返回任何内容

javascript - 使用 AJAX 提交表单并将数据以 JSON 形式发送到文件

javascript - 调用指令模板中的函数

javascript - ng-view 不显示路线(angularjs)

javascript - 带时间的日期选择器 HH :mm:ss

javascript - 带有可选参数的 Typescript 构建 URL