在Angular中控制器之间绑定数据

时间:2016-03-18 19:58:30

标签: javascript angularjs

不确定我是否正确这样做。我有两个控制器。一个人拉了所有帖子。另一个给了我垃圾桶里所有帖子的数量。它目前有效,但只有一种方式。如果我从垃圾桶中撤消帖子并将其放回群体中,则计数会更改以反映新号码,但如果我向垃圾箱发送帖子,则计数不会更新。

这是我的服务:

app.service('sharedProperties', function () {

});

这是我的第一个控制器:(此控制器提供所有帖子并具有垃圾功能)

app.controller('postsCtrl', function ($scope, $log, $http, $timeout, Data, $uibModal, sharedProperties) {
    Data.get('posts').then(function(data){
        $scope.posts = data.data;
        $scope.currentPage = 1; //current page
        $scope.filteredItems = $scope.posts.length; //Initially for no filter  
        $scope.totalItems = $scope.posts.length;
        $scope.list_pages = [
                {
                    id: '5',
                    name: '5'
                }, {
                    id: '10',
                    name: '10'
                }, {
                    id: '20',
                    name: '20'
                }, {
                    id: '50',
                    name: '50'
                }, {
                    id: '100',
                    name: '100'
                }
            ];
        $scope.maxSize = 5;
    });
    $scope.setPage = function(pageNo) {
        $scope.currentPage = pageNo;
    };
    $scope.filter = function() {
        $timeout(function() { 
            $scope.filteredItems = $scope.filtered.length;
        }, 10);
    };
    $scope.sort_by = function(predicate) {
        $scope.predicate = predicate;
        $scope.reverse = !$scope.reverse;
    };
    $scope.changePostStatus = function(post){
        post.approved = (post.approved=="1" ? "0" : "1");
        Data.put("posts/"+post.id,{approved:post.approved}).then(function (result) {
            Data.toast2(result);
        });
    };
    $scope.changePostAnnounce = function(post){
        post.announce = (post.announce=="1" ? "0" : "1");
        Data.put("posts/"+post.id,{announce:post.announce}).then(function (result) {
            Data.toast2(result);
        });
    };
    $scope.trashPost = function(post){
        if(confirm("Are you sure to remove the post")){
            Data.delete("posts/"+post.id).then(function(result){
                $scope.posts = _.without($scope.posts, _.findWhere($scope.posts, {id:post.id}));
                $scope.totalItems = $scope.posts.length;
                Data.toast(result);
            });
        }
    };
    $scope.open = function (p,size) {
        var modalInstance = $uibModal.open({
          templateUrl: 'views/postsEdit.html',
          controller: 'postsEditCtrl',
          size: size,
          resolve: {
            item: function () {
              return p;
            }
          }
        });
        modalInstance.result.then(function(selectedObject) {
            if(selectedObject.save == "insert"){
                $scope.posts.push(selectedObject);
                $scope.posts = $filter('orderBy')($scope.posts, 'id', 'reverse');
            }else if(selectedObject.save == "update"){
                p.title = selectedObject.title;
                // p.price = selectedObject.price;
                // p.stock = selectedObject.stock;
                // p.packing = selectedObject.packing;
            }
        });
    };

});

这是我的第二个控制器:(此控制器计算垃圾箱中的帖子)

app.controller('postsTrashCtrl', function ($scope, $log, $http, $timeout, Data, sharedProperties) {
    Data.get('trash').then(function(data){
        $scope.trash = data.data;
        $scope.totalTrashItems = $scope.trash.length;
    });

});

在控制器1中,trashPost函数是我尝试从控制器2更新totalTrashItems的地方

我知道这是我想念的小事。

更新

具有控制器和变量的HTML:

<div class="container">
        <div class="row" align="center">
            <div class="stats" ng-controller="postsTrashCtrl"><i class="fa fa-thumb-tack"></i> Total Posts (<span class="attendStat">{{ totalItems }}</span>)<span class="seperator">&nbsp;&nbsp;|&nbsp;&nbsp;</span><i class="fa fa-trash-o"></i> <a href="#/trash" id="trashCan" class="trashCan">Trash</a> (<span class="attendStat">{{totalTrashItems}}</span>)</div>
        </div>

1 个答案:

答案 0 :(得分:1)

我看到你那里有空服务。

没有深入了解您当前的代码。对于此上下文,我的控制器间通信解决方案是在Post,Trash和UnTrash事件上 $ broadcast(&#34; customEventName&#34;)

并且你的PostController和TrashPostController将使用 $ on(&#34; customEventName&#34;,function(){})订阅这些广播事件

使用一个PostTrackingService维护所有数据的发布和删除,甚至与服务器的通信。在这种情况下,如果需要通过发布和跟踪执行任何操作,您的控制器将简单地调用该服务。

我知道阅读有点冗长。我建议先看一下html,然后了解这些控制器是如何工作的,最后看一下如何定义服务。如果将此模式应用于代码。你的问题将得到解决。

这是代码。您还可以play with it on JSFiddle

<script src="https://code.angularjs.org/1.4.9/angular.min.js"></script>
<div ng-app="myApp">

  <div ng-controller="PostController">
    {{postCount}}
    <button ng-click="post()">
      Post
    </button>
    <button ng-click="trash()">
      Trash
    </button>
  </div>

  <div ng-controller="TrashController">
    {{trashCount}}
    <button ng-click="untrash()">
      UnTrash
    </button>
  </div>

</div>

<script>

var app = angular.module('myApp', []);

//----------------- Service to track all post changes ---------------
app.factory('PostTrackingService', function($rootScope) {
  var postCount = 10;
  var trashCount = 3;

  var _postTrackingService = {};

  _postTrackingService.getPostCount = function(){ return postCount};
  _postTrackingService.post = function(dataToPost){ 
    //do something with dataToPost

    postCount++;

    //broadcast a post event
    $rootScope.$broadcast("A custom POST event invented by me");
  };

  _postTrackingService.getTrashCount = function(){ return trashCount};
  _postTrackingService.trash = function(postId){
    //do something with postId

    trashCount++;
    postCount--;

    //broadcast a trash event
    $rootScope.$broadcast("A custom TRASH event invented by me");
  };

  _postTrackingService.untrash = function(postId){
    //do something with postId

    trashCount--;
    postCount++;

    //broadcast a trash event
    $rootScope.$broadcast("A custom UNTRASH event invented by me");
  };

  return _postTrackingService;
});



//----------------- Post Controller ---------------
app.controller("PostController", ["PostTrackingService", "$scope", "$rootScope", function(PostTrackingService, $scope, $rootScope){
    $scope.postCount = PostTrackingService.getPostCount();

  $rootScope.$on("A custom POST event invented by me", function(){
    $scope.postCount = PostTrackingService.getPostCount();
  });

  $rootScope.$on("A custom TRASH event invented by me", function(){
    $scope.postCount = PostTrackingService.getPostCount();
  });

  $rootScope.$on("A custom UNTRASH event invented by me", function(){
    $scope.postCount = PostTrackingService.getPostCount();
  });

  $scope.post = function(){
    PostTrackingService.post("some data to post to server");
  }

  $scope.trash = function(){
    PostTrackingService.trash("a post ID");
  }

}]);

//----------------- Trash Controller ---------------
app.controller("TrashController", ["PostTrackingService", "$scope", "$rootScope", function(PostTrackingService, $scope, $rootScope){
    $scope.trashCount = PostTrackingService.getTrashCount();

  $rootScope.$on("A custom TRASH event invented by me", function(){
    $scope.trashCount = PostTrackingService.getTrashCount();
  });

  $rootScope.$on("A custom UNTRASH event invented by me", function(){
    $scope.trashCount = PostTrackingService.getTrashCount();
  });

  $scope.untrash = function(){
    PostTrackingService.untrash("some post id");
    //make any calls to inform server
  }

}]);

</script>