5

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(){
  };
}])

2 Answers 2

5
 $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.

Sign up to request clarification or add additional context in comments.

1 Comment

alternatively he can do $scope.service = {}, then do things like $scope.service.foo = bar
4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.