Below is my HTML code along with JS script. I need to Change the value of "label" after the button click but it is not changing and using global values only.
http://plnkr.co/edit/T4EaZglOnq8Q2UVLWNFm?p=preview
My preview/Plnkr can be seen here..
JS CODE:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
$scope.year1=1992;
$scope.year2=1994;
$scope.year3=1996;
$scope.label=[$scope.year1,$scope.year2,$scope.year3];
$scope.splitYears = function()
{
$scope.year1=2202;
$scope.year3=2004;
$scope.year2=2001;
$scope.checking=[$scope.year1,$scope.year2,$scope.year3];
}
$scope.checking1=[$scope.year1,$scope.year2,$scope.year3];
});
1 Answer 1
You are never updating your $scope.label property inside of the click handler.
$scope.splitYears = {
$scope.year1=2202;
$scope.year3=2004;
$scope.year2=2001;
$scope.label=[$scope.year1,$scope.year2,$scope.year3];
$scope.checking=[$scope.year1,$scope.year2,$scope.year3];
}
You are also binding label to an array of objects, not an object directly.
As a result, there's no referenced value that is updated when you update your objects (since they're masked by the array) and AngularJS doesn't realize that it needs to update label.
If instead you bound $scope.label directly to $scope.year1, you would see label properly update on the UI.
Another option is to use a $watch/$watchCollection and automatically update your label outside of the click handler if your year changes.
$scope.array = [$scope.year1,$scope.year2,$scope.year3]
$scope.label = $scope.array;
$scope.$watchCollection("year1", function (newValue, oldValue) {
$scope.label = [$scope.year1, $scope.year2, $scope.year3];
});
$scope.splitYears = function() {
$scope.year1=2202;
$scope.year3=2004;
$scope.year2=2001;
$scope.checking=[$scope.year1,$scope.year2,$scope.year3];
}