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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments