2015-10-15 81 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。我有一個重定向到另一個尋呼機,其中指令有條件地呈現。 –