简体   繁体   中英

AngularJS: Initialize nested scope variables in controller

I like to keep my namespace of model names clean and descriptive, so I use nested model variables like this (where month and year are nested in service):

<form data-ng-submit="submit()">
  <select data-ng-model="service.month" data-ng-options="m for m in months"/>
  <input data-ng-model="service.year"/> {{ service.year }}
  <input type="submit"/>
</form>

And in my controller, I want to set $scope.service.month and $scope.service.year to initial values, but I get a javascript error Cannot set property 'year' of undefined , so I'm guessing the DOM hasn't been parsed and all the $scope variables haven't been created yet. How can I have some code wait to run until the DOM has been parsed by Angular and all the models have been created?

Here's my controller:

mod.controller('AddServiceCtrl', [
    '$scope', 
    '$rootScope', 
function($scope, $rootScope) {
  var date = new Date();
  $scope.months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  $scope.service.year = 2014;   
  $scope.submit = function(){
  };
}])
 $scope.service= {month:'Mar',year:2014};

AngularJS is still JavaScript.

The AngularJS team unfortunately chose to name what is actually a presenter (or a view model), a controller . It might not sound that important, but conceptually it is in order to understand what controllers do.

The problem is that the $scope.service object is undefined , so it is failing to define a year property on it inside the controller, not the view. To make this work, you must set service object on the scope like this:

$scope.service = {};

then you can define default values for the model on the controller or in the view:

Controller option

$scope.service = {};
$scope.service.year = 2014;

or

$scope.service = {
    year: 2014,
    month: $scope.months[3]   // to default to 'Apr'
};

View Option

<form data-ng-submit="submit()" 
      data-ng-init="service.year=2014; service.month=months[3]">
    ...
</form>

either way, you must create the service object on the scope in order to define properties thereon. use object literal notation ( {} ) to create it.

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