2015-10-15 83 views
0

我在客户类型的注册表单中有一个下拉列表。更改服务中的属性值angularjs

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

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

回答

0

比方说,你有你的下拉这样

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

在你的控制器:

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

就是这样。

+0

我尝试了你的建议方法,但没有运气。我做了以下工作:我提交了第一种类型的客户表单 - >指令已正确呈现。但是,当我改变客户类型时,指令就像我选择第一个选项而不是第二个选项一样呈现。 –

1

可以使用工厂方法,而不是服务如下 -

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>

这仅仅是用于更新服务价值POC。你可以在下拉菜单中实现类似的功能。

希望这可以帮助你!

+0

谢谢你的回复。如果启用重定向,此方法是否可行? –

+0

@ mr.M - 没有得到你的问题。你的意思是即使页面重新加载后更新后的值仍然存在? –

+0

yeap。我有一个重定向到另一个寻呼机,其中指令有条件地呈现。 –