【问题标题】:How to make the updated value in factory to be shown in DOM如何使工厂中的更新值显示在 DOM 中
【发布时间】:2017-10-29 21:59:31
【问题描述】:

请看示例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 显示剩余值。任何帮助都会很棒。

【问题讨论】:

    标签: javascript angularjs angular-factory


    【解决方案1】:

    当使用 $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

    此服务创建的间隔必须在以下情况下明确销毁 你已经完成了他们。特别是它们不会自动 当控制器的范围或指令的元素被销毁时 被摧毁。您应该考虑到这一点并确保 总是在适当的时候取消间隔。

    您可以通过以下方式确保间隔被销毁:

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

    【讨论】:

      猜你喜欢
      • 2017-10-25
      • 1970-01-01
      • 1970-01-01
      • 2018-06-07
      • 2014-11-21
      • 1970-01-01
      • 2011-06-03
      • 1970-01-01
      • 2020-10-05
      相关资源
      最近更新 更多