-2

see also JSFIDDLE demo

In this example, I am populating select options from an array of objects within another object. The selected value is also maintained inside this object:

function QuarterController($scope) {
    $scope.MyData = {
        Quarter: 2,
        QuarterArray: [{
            'value': 1,
            'text': 'Q1'
        }, {
            'value': 2,
            'text': 'Q2'
        }, {
            'value': 3,
            'text': 'Q3'
        }, {
            'value': 4,
            'text': 'Q4'
        }],
    };
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
<div ng-app>
     <h2>AngularJS ng-options Demo</h2>
    <p>Works in AngularJS 1.0.2 but not in 1.4.2.</p>
    <div ng-controller="QuarterController">
        <select name="quarter" ng-model="MyData.Quarter" ng-options="obj.value as obj.text for obj in MyData.QuarterArray">
            <option value="">Please select...</option>
        </select>
        <div>Quarter Selected: {{MyData.Quarter}}</div>
    </div>
    <p>What must I change to make this work in the latest AngularJS 1.*?</p>
</div>

If you change the AngularJS library from 1.0.2 to 1.4.2 it stops working. What must I do to make this work in the most recent 1.4.* or 1.5.* versions?

(thanks to BruteCode for the origins of this example)

Community
  • 1
  • 1
CAK2
  • 1,892
  • 1
  • 15
  • 17
  • 1
    Possible duplicate of [Angular is not recognizing global functions as controllers](http://stackoverflow.com/questions/29190214/angular-is-not-recognizing-global-functions-as-controllers) – m59 Oct 14 '15 at 04:38

1 Answers1

0

AngularJS 1.3 disabled the use of global variables as controllers by default. You have two options. For both of them you must add the name of the ng-app module to your html file:

    <div ng-app="myApp">
    </div>
  1. Either use the new syntax

    Add this to the bottom of your js file

    angular.module('myApp', []).controller('QuarterController', QuarterController);
    

    Working fiddle: https://jsfiddle.net/hp97e5ek/8/

  2. Or enable the functionality

    angular.module('myApp', []).config($controllerProvider) {
        $controllerProvider.allowGlobals();
    });
    

    Working fiddle: https://jsfiddle.net/hp97e5ek/9/

RJo
  • 15,631
  • 5
  • 32
  • 63