在没有$ scope或$ watch的Angular控制器上访问函数

时间:2017-01-04 09:56:37

标签: angularjs

我有以下服务,应该与许多控制器共享一个位置

angular.module("StockSampleApp")
.service("Location", function () {
    this.currentLocation;
})

我有一个主控制器,用于更改服务currentLocation。

angular.module("StockSampleApp")
    .controller("MainController",["Location",function (Location) {

        this.locations = [
            { Id: 1, Name: "UK Warehouse Group" },
            { Id: 2, Name: "Britania Warehouse" },
            { Id: 3, Name: "Warehouse Limited" }
        ];

        //Sets initial value for the service currentLocation variable
        Location.currentLocation = this.locations[0];

        //When location is changed it update the service currentLocation variable
        this.changeLocation = function (location) {
            Location.currentLocation = location;
        };

        this.getLocation = function () {
            return Location.currentLocation;
        };

    }]);

我有一个使用这些服务的网格控制器。当主控制器更新服务currentLocation时,我想运行GetData()

angular.module("StockSampleApp")
    .controller("GridController", ["Location", function (Location) {

        this.products = [];

        this.page = {
            totalProduct: 242,
            currentPage: 1,
            itemPerPage: 10
        };

        this.GetProducts = function(){
            this.products = [];

            for (var i = 0; i < this.page.itemPerPage;i++){
                //Makes Random Id
                var randomSkuId = (this.page.currentPage * 10) + i;

                this.products.push({
                    sku: randomSkuId,
                    title: "Product Title - " + randomSkuId,
                    onOrder: randomSkuId + 2,
                    due: randomSkuId - 2,
                    stockLevel: randomSkuId + 10,
                });
            };
        };

        this.GetProducts();

        this.pageChanged = function () {
            this.GetProducts();
        };

        this.getLocation = function () {
            //When location change update data in table - call GetProducts() and set currentPage = 1
            return Location.currentLocation;
        };

}]);

1 个答案:

答案 0 :(得分:2)

使用控制器时,AngularJS会自动为您提供 $ scope 的实例,我不明白不想使用已经提供的资源的原因,特别是当 $ scope 中的> $ watch 功能正是您实现目标所需的。

$scope.$watch(
  function () { return Location.currentLocation.id; },
  function (oldVal, newVal) {
    if (oldVal !== newVal) {
      // do stuff
    }
  }
);

如果您仍然不想使用它,可以使用此脏的变通方法定期检查您的服务是否已更新。

var currentLoc = Location.currentLocation;
setInterval(function () {
  if (Location.currentLocation.id !== currentLoc.id) {
    // do stuff then
    currentLoc = Location.currentLocation;
  }
}, 100); // adjust the interval to your taste

但我强烈反对这一点,因为上述解决方案简单明了