0

This code is not working and I can't tell why.

HTML

<select id="provincia" class="form-control" ng-model="ciudades" ng-options="provincia for (provincia, ciudades) in provincias">
 <option ng-model="valor_ciudad" value=''>Elegir</option>
</select>

JS

    $scope.$watch('ciudades', function(newval, oldval){
        debugger;
        if (newval){
            $scope.prov = newval;
        }
    });

What do I want to do? I am trying to get the value picked by user because the variable ciudades has an array of values.

$scope.provincias = {Florida:['Miami', 'Orlando']}

If the user picks Florida, then $scope.ciudades will be ['Miami', 'Orlando']. What I need to know is if the user choose Florida or another city. (.watch didn't work, not even stopping on debugger)

Did I make myself clear?

2

1 Answer 1

1

You can use the 'Florida' key as your key and value and set to the prov directly with the select's ng-model then, listen for prov changes and set ciudades based on the chosen key:

var app = angular.module('app', []);
app.controller('AppCtrl', function($scope, $compile, $timeout) { 
  $scope.provincias = {
    Florida: ['Miami', 'Orlando']
   };
  $scope.$watch('prov', function(newval, oldval){
    $scope.ciudades = $scope.provincias[newval];
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="AppCtrl">
  <select ng-model="prov" ng-options="key as key for (key, value) in provincias">
    <option ng-model="valor_ciudad" value=''>Elegir</option>
  </select>
  <br>
  $scope.prov: {{prov}}<br>
  $scope.ciudades: {{ciudades}}<br>
</div>

Sign up to request clarification or add additional context in comments.

1 Comment

You are the man! I still .watch not working on my code by I used ng-change and your code and it's working. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.