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(){
};
}])
Nested Controllers: AngularJS allows using nested controllers. It means that you have specified a controller in an HTML element which is a child of another HTML element using another controller.
In Angular 2.0, there will be no $scope .
scope(); $('#elementId'). scope(). $apply(); Another easy way to access a DOM element from the console (as jm mentioned) is to click on it in the 'elements' tab, and it automatically gets stored as $0 .
The $scope in an AngularJS is a built-in object, which contains application data and methods. You can create properties to a $scope object inside a controller function and assign a value or function to it. The $scope is glue between a controller and view (HTML).
$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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With