Sam Bush Sam Bush - 1 year ago 74
Javascript Question

AngularJS Proper way to pass variables

I would like to make them global so I can use

throughout the whole script. I will need each one to update independently but as I continue to add to the site I am going to need to use both together.
Live preview

  • Example does not work:
    $scope.shapeSelected =[color][shape];

  • Example does work:
    $scope.shapeSelected =[shape];

var app = angular.module("computer", ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
when('/main', {
controller: 'MainCtrl'
redirectTo: '/main'

.controller('MainCtrl', ['$scope', '$http', function($scope, $http) {

$scope.colorType = function(color) {
$http.get('stuff.json').then(function(response) {
$scope.colorSelected =[color];


$scope.shapeType = function(shape) {
$http.get('shapes.json').then(function(response) {
$scope.shapeSelected =[color][shape]; // <--- [color] is not getting pulled in on this function.

var resultsColorShape = $scope.shapeSelected; // <--- I would like to be able to store this incase i need it later.


Answer Source

You don't have to pass argument to your functions. if you defined ng-model="Color" you can use $scope.Color in your javascript code:

change in html:



and js to:

 $scope.colorType = function() {
 $http.get('stuff.json').then(function(response) {
     $scope.colorSelected =[$scope.Color];


 $scope.shapeType = function() {
     $http.get('shapes.json').then(function(response) {
         $scope.shapeSelected =[$scope.Color][$scope.Shape]; 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download