更改服务angularjs

时间:2015-10-15 14:59:21

标签: angularjs data-binding

我的客户类型的注册表中有一个下拉列表。

我想根据此下拉列表中的值呈现特定布局。为此,我创建了一个客户指令:

gasStation.directive('createMenuTree',['$log','customerType',function($log, customerType){

    var template;

    $log.debug(customerType.getCustomerType()+ ' from directive');

    if (customerType.getCustomerType() == 'REGULAR')  {template = 'dashboard/regular_dashboard.html';}
    if (customerType.getCustomerType() == 'BUSINESS') {template = 'dashboard/business_dashboard.html';}

    return{
        templateUrl: template
    }; }]);

我的控制员:

gasStation.controller('registrationController', ['$scope','$window','customerType', function($scope, $window, customerType){

    $scope.ProcessRegistration = function(){
        var url = "http://" + $window.location.host +'/pages/index.html#'+'/dashboard';
        $window.location.href = url;      
        customerType.setCustomerType($scope.customerType); 
    };    

}]); 

我的服务:

gasStation.service('customerType',function(){

    var customerType;

    return{

        getCustomerType: function(){ return customerType; },
        setCustomerType: function(type){ customerType = type; }

    };
});

但是,根据文档,所有服务对象都是单例。

问题是:如何根据下拉列表中的选定值更新服务变量customerType

2 个答案:

答案 0 :(得分:2)

您可以使用Factory方法代替Service,如下所示 -



app = angular.module('myApp',[]);
  app.factory('customerType',function(){

    var customerType;

    return{

        getCustomerType: function(){ return customerType; },
        setCustomerType: function(type){ customerType = type; }

    };
});
app.controller('myCtrl', ['$scope','customerType', function($scope,customerType){

  $scope.cType = 'Retail';

  $scope.update = function(val){
    customerType.setCustomerType(val);
    $scope.cType = customerType.getCustomerType(val);
  };
 
}]);

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">



<div ng-controller="myCtrl">
  <input type="text" ng-model="t">
  <button type="button" ng-click="update(t)"> Change</button>

  <pre>Customer Type : {{cType}}</pre>
</div>
&#13;
&#13;
&#13;

这只是用于更新服务价值的POC。你可以在下拉列表中实现类似的东西。

希望这对你有所帮助!

答案 1 :(得分:0)

假设您有这样的下拉列表

<select ng-model='model.customerType' ng-change='customerChanged()' ..... />

在您的控制器中:

$scope.customerChanged = function(){
   customerType.customerType = model.customerType;
}

就是这样。