如何使工厂中的更新值显示在 DOM 中

How to make the updated value in factory to be shown in DOM

请看例子here。我希望 dom 每秒更新一次。

var myApp = angular.module("myApp", ['ui.bootstrap']);
myApp.factory("productCountFactory", function() {
  var total = 0
  setInterval(function checkItems(){
            total++;
        }, 1000);

    var add =function(){
      total++
    }
  return {
    totalProducts: function(){
      return total
    },
    add: add
  };
});

目前只有当我点击添加按钮时它才会更新。

这只是一个例子。我想要实现的是,超时后,我想从数组中删除某些元素并使用 ng-repeat 显示剩余的值。任何帮助都会很棒。

当使用 $interval service 而不是本机 setInterval()

时,您将实现此目的

// Code goes here

var myApp = angular.module("myApp", ['ui.bootstrap']);
myApp.factory("productCountFactory", function($interval) {
  var total = 0
  $interval(function checkItems() {
    total++;
  }, 1000);

  var add = function() {
    total++
  }
  return {
    totalProducts: function() {
      return total
    },
    add: add
  };
});
myApp.controller("welcomeContoller", function($scope, productCountFactory) {
  $scope.productCountFactory = productCountFactory;
});

myApp.controller("productController", function($scope, productCountFactory) {
  $scope.addProduct = function() {
    console.log(productCountFactory.totalProducts());
    productCountFactory.add();
    console.log(productCountFactory.totalProducts());
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script data-require="ui-bootstrap@*" data-semver="1.1.1" src="https://cdn.rawgit.com/angular-ui/bootstrap/gh-pages/ui-bootstrap-1.1.1.js"></script>
<link data-require="bootstrap-css@3.3.6" data-semver="3.3.6" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" />

<body ng-app="myApp">
  <div ng-controller="welcomeContoller">
    {{productCountFactory.totalProducts()}}
  </div>
  <hr>
  <div ng-controller="productController">
    <div class="addRemoveCart">
      <button ng-click="removeProduct()">Remove</button>
      <button ng-click="addProduct(1)">Add</button>
    </div>
  </div>
</body>

但请注意:

source

Intervals created by this service must be explicitly destroyed when you are finished with them. In particular they are not automatically destroyed when a controller's scope or a directive's element are destroyed. You should take this into consideration and make sure to always cancel the interval at the appropriate moment.

您可以确保间隔被销毁,例如:

var myInterval = $interval(someFunction);

$scope.$on('$destroy', function() {
    if (angular.isDefined(myInterval)) {
        $interval.cancel(myInterval);
        myInterval = undefined;
    }
});