0

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>

1 Answer 1

1

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>

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

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.