AngularJS: Sharing scope between multiple instances of same directive

旧巷老猫 提交于 2020-01-14 04:47:06

问题


I'm writing an app that uses the same table with the same data in multiple places. I created a custom directive that allows me to reuse this table. Unfortunately, if I edit the table in one instance, the other instance does not refresh. How do I link these two so that any edits I make to one show up in the other?


回答1:


It sounds like you've mostly figured it out, the hard part is getting your data into a shape where the videos and photos can be shared by the slide show. I recommend doing this in a shared data access object returned by a separate factory in Angular, rather than directly in a scope. I've got a sample in Plunkr if it helps.

The sample has a directives that binds to shared data, retrieved from a factory as an object injected into two separate scopes. In your case, you would have to add methods to retrieve data from the server, and shape it for display.

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;
}]);

Both controllers reference the same factory for the data:

testApp.controller("FirstController", 
  ["$scope", "News", function ($scope, news) {
    $scope.news = news;
}]);

testApp.controller("SecondController", 
  ["$scope", "News", function ($scope, news) {
    $scope.news = news;
}]);

Views then pass the data into to the news list directive, which both shares the data and keeps the directive relatively dumb.

  <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>

The news-list directive is just dumb formatting in this example:

testApp.directive("newsList", 
  function() {
    var directive = {
      "restrict": "E",
      "replace": false,
      "templateUrl": "news-list.html",
      "scope": {
        "news": "=news",
        "title": "=title"
      } 
    };
    return directive;
});

View template:

<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>


来源:https://stackoverflow.com/questions/28814163/angularjs-sharing-scope-between-multiple-instances-of-same-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!