Reputation: 15
I try it like bellow but result is "undefined"
Please help me
Here is code :
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl" ng-init="carname='Volvo'">
<h1>{{carname}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
//I want to get value of $scope.carname here
alert($scope.carname);
});
</script>
Upvotes: 0
Views: 26
Reputation: 222532
That's the default behaviour because the controller gets created first and then carname='Volvo'
is set.
as a work around, you should use a function as below instead,
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.init = function(carName) {
$scope.carname = carName;
alert($scope.carname);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl" ng-init="init('Volvo')">
<h1>{{carname}}</h1>
</div>
Upvotes: 1