StarTrek18
StarTrek18

Reputation: 323

Cannot read property 'selection' of undefined in AngularJS

I am having troubles linking the inputs of my form into a defined factory that I have injected into the controller that renders the form. Here is my factory:

App.factory('DeviceSelection',function() {
   var states=[{selection:{}},{selection:{}},{selection:{}},{selection:{}}];
   return states;
});

And here is an input of my form:

            <div class="controls">
              <label class="radio">
                <input type="radio" name="user[role]" id="user_role_managing_editor" value="Managing editor" ng-model='states[0].selection.hours'>
                Yes 
              </label>
              <label class="radio">
                <input type="radio" name="user[role]" id="user_role_area_editor" value="Area editor", ng-model='states[0].selection.hours'>
                No 
              </label>
            </div>

So, when I try to click on that Radio box, I see the following in the JS Console:

TypeError: Cannot read property 'selection' of undefined

Does that mean that I need to initialize the model before the view is rendered. If so, where?

I am trying to achieve a multi-step form, linking all the inputs in the model, until last step is reached when I am able to send the results to an API. As asked here:

Store status between forms in AngularJS?

Upvotes: 1

Views: 1870

Answers (1)

Nobita
Nobita

Reputation: 23713

You say that you have injected in your controller. It would be nice to see that injection, but let me blind guess something that might be happening:

I am assuming you have (something like) this:

YourApp.controller('YourController', ['$scope', 'YourFactory', function ($scope,$yourFactory) {
...

But, have you set that injection into the $scope? Otherwise the view won't have access :)

So, if you don't have it, do this:

 $scope.states=$yourFactory;

I really believe this is what happened. The controller needs to tell the view where to find that state array through the $scope

Upvotes: 2

Related Questions