【问题标题】:Correct way to set property in Angular Factory在 Angular Factory 中设置属性的正确方法
【发布时间】:2015-07-22 10:03:24
【问题描述】:

在 Angular 工厂中创建将由视图 X 中的控制器设置并由同一控制器使用视图 Y 获取的 get/set 属性的最佳做法是什么?我应该像下面这样使用 $rootScope 吗?

工厂:

angular.module('start.services').factory('bluetoothFactory', ['$q', '$window', '$rootScope', function($q, $window, $rootScope) {
 return {

  connectedDeviceSet:  function(device)
  {
    $rootScope.connectedDevice = device;
  },
  connectedDeviceGet: function()
  {
    return $rootScope.connectedDevice;
  },
...

控制器:

angular.module('start.controllers',[]).controller('bluetoothCtrl', function($scope, $ionicModal, $timeout, bluetoothFactory) 
{
...
$scope.list = function()
  {
    bluetoothFactory.list().then(function(data)
    {
      $scope.info = data;
      if (data.length > 0)
      {
        bluetoothFactory.connectedDeviceSet = data[0];
      }
    }, 
    function(error) 
    { 
      $scope.error = error;
    });
  };
$scope.readEPCForEncoding = function() 
{
   var device = bluetoothFactory.connectedDeviceGet;
   ....
}

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    您应该使用服务而不是工厂。服务应该定义为prototype——在其他语言中翻译成class。尽量不要访问您的工厂或服务中的 $rootScope。这意味着您没有正确封装您的属性。这会导致冲突和奇怪的错误。

    var app = angular.module('app', []);
    
    function Bluetooth() {
      this.connectedDevice;
    }
    
    Bluetooth.prototype.setConnectedDevice = function(value) {
      this.connectedDevice = value;
    }
    
    Bluetooth.prototype.getConnectedDevice = function() {
      return this.connectedDevice;
    }
    app.service('bluetooth', Bluetooth);
    
    
    DeviceController.$inject = ['bluetooth'];
    function DeviceController(bluetooth) {
      this.bluetooth = bluetooth;
      
      this.device;
    }
    
    DeviceController.prototype.getDevice = function() {
      this.device = this.bluetooth.getConnectedDevice(); 
    }
    
    app.controller('DeviceController', DeviceController);
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="app">
      
      <div ng-controller="DeviceController as vm1">
        
        Controller 1: <br><br>
        
        <button ng-click="vm1.bluetooth.setConnectedDevice('Device set from instance one')">Set Device</button>     
        <br/><br>
        <button ng-click="vm1.getDevice()">Get Device</button>
        <br/><br>
        Device: {{vm1.device}}
        
        <br>
        Device in Service: {{vm1.bluetooth.connectedDevice}}
        
      </div>
      
      <br/> <br/>
      
      <div ng-controller="DeviceController as vm2">
        
        Controller 2: <br><br>
        
        <button ng-click="vm2.bluetooth.setConnectedDevice('Device set from instance Two')">Set Device</button>     
        <br/><br>
        <button ng-click="vm2.getDevice()">Get Device</button>
        <br/><br>
        Device: {{vm2.device}}
        
        <br>
        Device in Service: {{vm2.bluetooth.connectedDevice}}
        
      </div>
    
    </div>

    然后在您的控制器中,如果您可以代理 set 和 get 方法或将 bluetooth 服务公开给视图。

    点击控制器的两个实例中的按钮,观察设备是如何设置的。

    【讨论】:

    • 我的回答仍然有效。不要使用 $rootScope。使用带有构造函数的服务和添加到构造函数原型的方法。
    • 当我调用 getConnectedDevice 时,我得到了 null。 setConnectedDevice 正在填充对象。但请记住,set 是从控制器 X 发生的,而 get 是从控制器 Y 执行的。
    • 所以你可以在我的答案中运行这个例子。您将看到控制器有两个实例。每个都在服务中公开设备并且可以设置设备。有关另一个工作示例,请参阅:stackoverflow.com/questions/27720707/…
    【解决方案2】:

    你应该这样写。

    angular.module('start.services').factory('bluetoothFactory', ['$q', '$window', '$rootScope', function($q, $window, $rootScope) {
    
     return {
      connectedDevice : null,       
      connectedDeviceSet:  function(device)
      {
        this.connectedDevice = device;
      },
      connectedDeviceGet: function()
      {
        return this.connectedDevice;
      },
    

    不需要$rootScope,因为它违反了全局范围。

    请参考此Plunker 以获得更好的理解。检查 script.js

    设置

    bluetoothFactory.connectedDeviceSet(dataishere);

    得到

    var dataishere = bluetoothFactory.connectedDeviceGet();
    

    【讨论】:

    • 谢谢。然后我就可以将它作为我的控制器简单地用作 bluetoothFactory.connectedDeviceGet?
    • 我明白了。问题是控制器先是从视图X中设置connectedDevice,然后从视图Y中获取connectedDevice。当我在 Y 中获取 connectedDevice 时,我得到一个空对象。
    【解决方案3】:

    如果您想在每个控制器中都使用相同的数据,那么简单而有效。并且您不需要将数据存储在最糟糕的$rootScope 中。

    app.factory('bluetoothFactory', function($http) {
        function Test() {
            var context = this;
            this.data= [];
            this.connectedDeviceGet= function() {
                    return this.data;
            };
           this.connectedDeviceSet= function(data) {
                    this.data = data;
            };
        }
        //get instance
        var self;
    
        function get() {
            if (self) {
                return self;
            } else {
                var self = new Test();
                return self;
            }
        }
    
        return {
            get: get
        };
    
    });
    
    
    //can access like this.
    app.controller('testCtrl',function(bluetoothFactory){
        var service = bluetoothFactory.get();
        service.connectedDeviceSet([1,2]);
    });
    

    【讨论】:

    • 抱歉,我对 Angular 很陌生。该示例将如何转化为我的代码?
    猜你喜欢
    • 2012-01-18
    • 2018-09-29
    • 1970-01-01
    • 1970-01-01
    • 2013-01-19
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    相关资源
    最近更新 更多