简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM