0

请看这里的例子。我希望 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 显示剩余值。任何帮助都会很棒。

4

1 回答 1

1

当使用$interval 服务而不是本机服务时,您将实现这一点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>

但请注意:

资源

此服务创建的间隔必须在您完成后明确销毁。特别是当控制器的作用域或指令的元素被销毁时,它们不会自动销毁。您应该考虑到这一点,并确保始终在适当的时候取消间隔。

您可以通过以下方式确保间隔被破坏:

var myInterval = $interval(someFunction);

$scope.$on('$destroy', function() {
    if (angular.isDefined(myInterval)) {
        $interval.cancel(myInterval);
        myInterval = undefined;
    }
});
于 2017-10-29T22:07:39.677 回答