2015-10-15 3 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. У меня есть перенаправление на другой пейджер, где директива условно отображается. –