ArunJaganathan ArunJaganathan - 1 month ago 14
AngularJS Question

Working with .$on in angular js

How to get the current value in my html page using $on ?
My code is :

$scope.$on('slideEnded', function() {
var startClass, endClass, sPos,ePos;
startClass = $scope.componentDetails.stepArray[$scope.componentDetails.value];
endClass = $scope.componentDetails.stepArray[$scope.componentDetails.maxVal];


// console.log(startClass + endClass)
getBatchSliders(startClass, endClass)

});


function getBatchSliders(startClass, endClass) {
endClass=parseInt(endClass);
var totalSlider;

if (startClass !== 'LKG' || startClass !== 'UKG') {
totalSlider = endClass;
//console.log("LKG not found")
}
if (startClass === 'LKG') {
totalSlider = endClass + 2
//console.log("LKG found")
}
$scope.totalSliders=totalSlider;
console.log($scope.totalSliders)
}


Now I want to pass "totalSliders" value to my html page ?
When I used this {{totalSliders}} its not get the current value?

Answer

Since you are assigning a value to totalSliders, the binding will be lost after the first time you set it.

Use a view model object to persist the state:

$scope.vm = {}; // <-------------- initialize the vm here

$scope.$on('slideEnded', function() {
    var startClass, endClass, sPos,ePos;
    startClass = $scope.componentDetails.stepArray[$scope.componentDetails.value];
    endClass = $scope.componentDetails.stepArray[$scope.componentDetails.maxVal];    


    // console.log(startClass + endClass)
    getBatchSliders(startClass, endClass)
 });


function getBatchSliders(startClass, endClass) {
    endClass=parseInt(endClass);
    var totalSlider;

    if (startClass !== 'LKG' || startClass !== 'UKG') {
        totalSlider = endClass;
        //console.log("LKG not found")
    }
    if (startClass === 'LKG') {
        totalSlider = endClass + 2
        //console.log("LKG found")
    }
    $scope.vm.totalSliders = totalSlider;  //  <--------------  use the vm here
    console.log($scope.vm.totalSliders)
 }

Then bind to {{vm.totalSliders}} instead of just {{totalSliders}}

Comments