karanusret
karanusret

Reputation: 15

How do I access $scope variable in script code that I initiated with ng-init

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

Answers (1)

Sajeetharan
Sajeetharan

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

Related Questions