我正在编写一个应用程序,该应用程序在多个位置使用相同的数据表。我创建了一个自定义指令,允许我重用此表。不幸的是,如果我在一个实例中编辑表,则另一个实例不会刷新。如何链接这两个以便我对其中一个进行的编辑显示在另一个?
答案 0 :(得分:2)
该示例具有绑定到共享数据的指令,从工厂检索为注入两个单独范围的对象。在您的情况下,您必须添加从服务器检索数据的方法,并对其进行整形以便显示。
testApp.factory("News", [function () {
var news = {
"stories": [
{"date": new Date("2015-03-01"), "title": "Stuff happened"},
{"date": new Date("2015-02-28"), "title": "Bad weather coming"},
{"date": new Date("2015-02-27"), "title": "Dog bites man"}
],
"addStory": function (title) {
var story = {
"date": new Date(),
"title": title
};
news.stories.push(story);
}
};
return news;
}]);
两个控制器都为数据引用相同的工厂:
testApp.controller("FirstController",
["$scope", "News", function ($scope, news) {
$scope.news = news;
}]);
testApp.controller("SecondController",
["$scope", "News", function ($scope, news) {
$scope.news = news;
}]);
然后,视图将数据传递给新闻列表指令,该指令共享数据并使指令相对愚蠢。
<div ng-controller="FirstController">
<news-list news="news" title="'First List'"></news-list>
</div>
<div ng-controller="SecondController">
<news-list news="news" title="'Second List'"></news-list>
</div>
在这个例子中,news-list指令只是简单的格式化:
testApp.directive("newsList",
function() {
var directive = {
"restrict": "E",
"replace": false,
"templateUrl": "news-list.html",
"scope": {
"news": "=news",
"title": "=title"
}
};
return directive;
});
查看模板:
<div class="news-list">
<p>{{title}}</p>
<ul>
<li ng-repeat="story in news.stories | orderBy:'date':true">{{story.date | date:'short'}}: {{story.title}}</li>
</ul>
<form>
<input type="text" id="newTitle" ng-model="newTitle" />
<button ng-click="news.addStory(newTitle)">Add</button>
</form>
</div>