Reputation: 41
i'am trying to understand this behaviour: when I change the input the view change too but when I click on button the alert box don't change the $scope.firstName. Thanks for give me advices. regards
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
var test=$scope.firstName;
$scope.test=function(){
alert(test);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
Full Name: {{firstName + " " + lastName}}
<button ng-click="test()">Click</button>
</div>
Upvotes: 2
Views: 1047
Reputation: 365
Your test variable is only initialized once with John Doe values.
to make sure your alert displays updarted values, you could directly access your $scope variables as suggested in the previous answer OR put a $watch
on the scope.
$watch
service actually watches for changes in the $scope then applies a set of instructions, example:
$scope.$watch('firstname', function() {
test=$scope.firstName;
});
Each time firstname changes, the function will update test value and then the alert will display updated value
Upvotes: 0
Reputation: 2354
Currently, when you launch your controller, you are doing 3 things :
$scope.firstName = "John";
$scope.lastName = "Doe";
var test=$scope.firstName;
So your var test is initialize only when you launch your controller not when you laucnh your function. Your funtion, only print this value.
If you want print the current version of your scope, you need to do this :
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
$scope.test=function(){
alert($scope.firstName);
};
});
Upvotes: 3