Sam Bush Sam Bush - 3 months ago 7
AngularJS Question

how to pass a varible from an option from to my Controller?

Can someone show me how to gather the value select on.change of the dropdown box and then use that value as a varible in my controller.
for some reason the $ColorPicked varible will not revolve in the $scope.base = response.data.type.$ColorPicked; BUT if i just remove the $ColorPicked and type in Red it works no problem.

I am still very new to Angular and JS for that matter so please excuse my stupidity. I have Googled and Googled for a clear cut answer and I got nothing.

INDEX.HTML
<h3>Color:</h3>
<select class="formBoxes" id="ColorPicked">
<option value="Red">Redd</option>
<option value="Blue">Blue</option>
<option value="Green">Green</option>
</select>

SCRIPT.JS
$ColorPicked = "Red";

var app = angular.module("computer",['ngRoute'])
.config(['$routeProvider', function($routeProvider){
$routeProvider.
when('/main',{
templateUrl: 'archetype.html',
controller:'MainCtrl'
}).
otherwise({redirectTo:'/main'})
}])

.controller('MainCtrl', ['$scope', '$http', function($scope, $http){
$http.get('archetype.json').then(function(response){

$scope.base = response.data.type.$ColorPicked;

;
});
}]);

Answer

There are two things,

(i)You need to have a $scope variable defined for the ColorPicked inorder to provide the default selection.

(ii)You need to have ng-model which gets bind to the variable. Pass the selected Color to the function using the ng-change directive

HTML:

 <select ng-model="ColorPicked" ng-change="setItem(ColorPicked)">
      <option>Red</option>
      <option>Blue</option>
      <option>Green</option>    
  </select>

Controller:

function MyCtrl($scope) {
    $scope.ColorPicked = "Red";    
    $scope.setItem = function(opt) {
    $scope.base =opt;
  }
}

DEMO

Working Demo for your requirement