Search code examples
javascriptangularjsangularjs-scope

$scope.value change in the same function


Hello I'm new to Angular and JS so may be this is a known issue or a dumb bug that i made, so i have this controller in which i have this function :

        $scope.companies = [];                      
        $scope.BindCompanies = function()
        {
            $scope.companies = JSON.parse( localStorage.getItem( Const.CacheKeys.Companies ) )
            if($scope.companies.length = 0){
                companyService.getAll()
                .then(
                    function (response) 
                    {
                        localStorage.setItem(Const.CacheKeys.Companies, JSON.stringify( response.data.d.results ))
                        $scope.companies = response.data.d.results;

                        setDataTableData();
                    }
                );                  
            }
            else{
                setDataTableData();
            }
        }

the problem is that on execution $scope.companies contains data so it continue to else and there $scope.companies is empty !

thank you.


Solution

  • Single = is an assignment operator. So each time in your code,

    if($scope.companies.length = 0)

    the if blocks will execute to false as 0 is equivalent to false

    Change you if block like this -

    if($scope.companies.length == 0)