Sarang Pahurkar
Sarang Pahurkar

Reputation: 3

$scope variable is not getting updated on view which rendered using $state

Below is app.js file contain myApp module. I am facing issue with $scope variable not updated on view file which is rendered using $state. I am calling showArticles function on ng-change event from one of view file which got rendered using $state.go statement. This view rendered after user login. All code snap given below. Also facing same issue after AJAX success response $scope not getting updated on view file.

var myApp = angular.module('myApp', ['ui.router']);
myApp.config(function($stateProvider, $urlRouterProvider){
    $stateProvider.state('settings', {
        url: '/settings',
        templateUrl: 'templates/setting.html',
        controller: 'adminCtrl', 
    })
    .state('profile', {
        url: '/profile',
        templateUrl: 'templates/profile.html',
        controller: 'adminCtrl',
    })
    .state('account', {
        url: '/account',
        templateUrl: 'templates/account.html',
        controller: 'adminCtrl',
        cache: false
    })
    .state('articleList', {
        url: '/articles',
        controller: 'adminCtrl',
        cache: false,
        templateUrl: 'templates/articleList.html',

    })
    .state('addArticle', {
        url:'/addArticle',
        templateUrl : 'templates/addArticle',
        controller: 'adminCtrl',
        cache: false
    })

    $urlRouterProvider.otherwise('/settings');
});



myApp.run(function($rootScope, $state, $location, AuthenticationService){

    //array of route that dont need authentication
    var routeThatDontNeedAuth = ['/settings'];

    var routeClean = function(route)
    {
        //alert(route); alert();
        if(routeThatDontNeedAuth.indexOf(route) !== -1){ alert('aaa');
            return false;
        }
        else{
            return true;
        }
    }


    $rootScope.$on('$stateChangeStart', function(event, next, current){

        if(routeThatDontNeedAuth.indexOf($location.url()) < 0)
        {           
            if(!AuthenticationService.isLoggedIn()){
                //$state.go('settings');
               //alert('not logged in and page is not login page');
            }
        }   
    });
});

myApp.factory('AuthenticationService', ['$http', '$state', function($http, $state){

    return{
        isLoggedIn: function(){ alert('Aut ser called');
            $http({
                url: 'http://127.0.0.1:8081/cUlI',
                method: 'GET'
            }).then(function(response){
                alert('testtt');console.log(response);
                if(!response.data.loggedIn)
                {
                    $state.go('settings');
                }

            })      
        }
    };
}]);




            myApp.controller('adminCtrl', ['$scope', '$http', '$state', 'getArticleData', function($scope, $http, $state, getArticleData){

                $scope.addArticle = function(){
                    $state.go('addArticle');
                }
                // get website list     


                $scope.showArticles = function(){

                /*$scope.articleList = 'this is default article scope value';
                alert($scope.articleList)
                $scope.$applyAsync(function() {
                $scope.articleList = "Another value rest"; alert($scope.articleList)
            });*/

                    $http({
                            method: "GET",
                            url: "http://127.0.0.1:8081/articleList",
                            params: {
                                website:$scope.website
                            }
                            }).then(function(responseData){
                                if(responseData.data.status == 'success')
                                { 
                                    console.log('test dataaa');
                                    console.log(responseData);
                                    alert('page should modified')
                                    alert('This is test');
                                    $scope.articleList = {id:'test', name: 'article list'};//responseData.data.data;
                                    $scope.artLs = "I am testt model";
                                    $state.go('articleList', 'cache: false');   
                                }

                            })



                }

                $scope.adminLogin = function(){ 
                    var uname = $scope.username;
                    var pass  = $scope.password ;
                                alert(uname+'--'+pass); 
                    $http({
                            method : "GET",
                            url : "http://127.0.0.1:8081/adminLogin",
                            params: {
                                username : uname,
                                pwd: pass
                            }
                        }).then(function(response) {

                            console.log('succes',response);
                            if(response.data.status == 'success')
                            {
                                $http({
                                method: "GET",
                                url: "http://127.0.0.1:8081/webSiteList"
                                }).then(function(responseData){

                                    if(responseData.data.status == 'success')
                                    { 

                                        $scope.sara = 'testsara';
                                        $scope.websiteData = {id : 'a', name: 'test'}; // responseData.data.data;
                                        console.log('scope website data', $scope.websiteData);

                                        $state.go('account', 'cache: false');
                                    }

                                });


                            }
                            else
                            {

                            }
                        }, function(response) {
                            console.log('error',response)
                        });



                }
            }]);

showArticles functions get called on ng-change event from account view:

<div id="main-container" class="col-md-12  container" >
    <div class="col-md-1"></div>
    <div class="col-md-10">
        <div class="main-body">
            <div class="content"> 

                <div class="col-md-2"></div>
                <div class="col-md-8">
                    <h2 class="text-center">Article Listing page modified</h2>
                    <div class="vt-add-article">
                        <button type="button" ="btn btn-default text-center" ng-click="addArticle();">Add</button>
                    </div>
                    <div class="vt-article-list">
                    {{articleList}} 

                    <br>
                    {{artLs}} -- exp value
                    </div>
                </div>
                <div class="col-md-2"></div>
            </div>
        </div>
    </div>
    <div class="col-md-1"></div>
</div>

Main Index .html file :

 <html>
    <head>
    <meta charset="utf-8">
        <title>Welcome to Vidarbha Tigers Content Panel</title>
         <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        <link rel="stylesheet" href="/angularp/router/css/admin.css" />
        <script src="/angularp/router/js/angular.min.js"></script>
        <script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
        <script src="/angularp/router/js/app.js"></script>


    </head>
     <body ng-app="myApp" ng-controller="adminCtrl">
     <header>

        <div class="col-md-12">
            <div class="col-md-1"></div>
            <div class="vt-header-content col-md-10">
                <div class="vt-header-logo">
                    <!--<img src="/images/logo.jpg" class="img-rounded" alt="Vidarbha Tiger"> -->
                </div>
                <div class="vt-header-tag"><h2><!--Vidarbha Tigers--></h2></div>

            </div>
            <div class="col-md-1"></div>

        </div>
        <hr/>
    </header>
            <div ui-view></div>
        </body>

    </body>
    </html>

Kindly let me know if I am missing anything in my code. I am new to angular js and facing few issues which are unknown to me

Upvotes: 0

Views: 527

Answers (2)

AshishU
AshishU

Reputation: 41

ok, I understand your issue. Your $scope variable is getting reset everytime you call a view. Hence, you dont see any value. You will have to save the value and then retrieve it when your view gets loaded. I have updated your code below, try and let me know if it works or not

SOLUTION 1: Create one more factory:

myApp.factory('persistService', ['$rootScope', function($rootScope){

var articleList = '';
return{
    saveArticleList: function(data) {
      articleList = data;
    },
    getArticleList: function() {
      return articleList;
    }
};
}]);

Then in your controller include the above service and save the articleList and when you go to your new view, intialize your articleList using the 'persistService' as below :

myApp.controller('adminCtrl', ['$scope', '$http', '$state', 'persistService', 'getArticleData', function($scope, $http, $state, getArticleData, persistService){

           //Initialize your articleList
           $scope.articleList = persistService.getArticleList();

            $scope.addArticle = function(){
                $state.go('addArticle');
            }
            // get website list     


            $scope.showArticles = function(){

            /*$scope.articleList = 'this is default article scope value';
            alert($scope.articleList)
            $scope.$applyAsync(function() {
            $scope.articleList = "Another value rest"; alert($scope.articleList)
        });*/

                $http({
                        method: "GET",
                        url: "http://127.0.0.1:8081/articleList",
                        params: {
                            website:$scope.website
                        }
                        }).then(function(responseData){
                            if(responseData.data.status == 'success')
                            { 
                                console.log('test dataaa');
                                console.log(responseData);
                                alert('page should modified')
                                alert('This is test');

                                //Save your data
                                persistService.setArticleList('This is a test');
                                //$scope.articleList = {id:'test', name: 'article list'};//responseData.data.data;
                                $scope.artLs = "I am testt model";
                                $state.go('articleList', 'cache: false');   
                            }

                        })



            }

            $scope.adminLogin = function(){ 
                var uname = $scope.username;
                var pass  = $scope.password ;
                            alert(uname+'--'+pass); 
                $http({
                        method : "GET",
                        url : "http://127.0.0.1:8081/adminLogin",
                        params: {
                            username : uname,
                            pwd: pass
                        }
                    }).then(function(response) {

                        console.log('succes',response);
                        if(response.data.status == 'success')
                        {
                            $http({
                            method: "GET",
                            url: "http://127.0.0.1:8081/webSiteList"
                            }).then(function(responseData){

                                if(responseData.data.status == 'success')
                                { 

                                    $scope.sara = 'testsara';
                                    $scope.websiteData = {id : 'a', name: 'test'}; // responseData.data.data;
                                    console.log('scope website data', $scope.websiteData);

                                    $state.go('account', 'cache: false');
                                }

                            });


                        }
                        else
                        {

                        }
                    }, function(response) {
                        console.log('error',response)
                    });



            }
        }]);

Let me know if this helps!

EDIT:: SOLUTION 2: There is another way you can accomplish the same just by making a change in your controller code. See below code:

myApp.controller('adminCtrl', ['$scope', '$http', '$state', 'getArticleData', function($scope, $http, $state, getArticleData){

           //Initialize your articleList
           $scope.articleList = $scope.articleList || {};

            $scope.addArticle = function(){
                $state.go('addArticle');
            }
            // get website list     


            $scope.showArticles = function(){

            /*$scope.articleList = 'this is default article scope value';
            alert($scope.articleList)
            $scope.$applyAsync(function() {
            $scope.articleList = "Another value rest"; alert($scope.articleList)
        });*/

                $http({
                        method: "GET",
                        url: "http://127.0.0.1:8081/articleList",
                        params: {
                            website:$scope.website
                        }
                        }).then(function(responseData){
                            if(responseData.data.status == 'success')
                            { 
                                console.log('test dataaa');
                                console.log(responseData);
                                alert('page should modified')
                                alert('This is test');

                                //Save your data
                                $scope.articleList = {id:'test', name: 'article list'};//responseData.data.data;
                                $scope.artLs = "I am testt model";
                                $state.go('articleList', 'cache: false');   
                            }

                        })



            }

            $scope.adminLogin = function(){ 
                var uname = $scope.username;
                var pass  = $scope.password ;
                            alert(uname+'--'+pass); 
                $http({
                        method : "GET",
                        url : "http://127.0.0.1:8081/adminLogin",
                        params: {
                            username : uname,
                            pwd: pass
                        }
                    }).then(function(response) {

                        console.log('succes',response);
                        if(response.data.status == 'success')
                        {
                            $http({
                            method: "GET",
                            url: "http://127.0.0.1:8081/webSiteList"
                            }).then(function(responseData){

                                if(responseData.data.status == 'success')
                                { 

                                    $scope.sara = 'testsara';
                                    $scope.websiteData = {id : 'a', name: 'test'}; // responseData.data.data;
                                    console.log('scope website data', $scope.websiteData);

                                    $state.go('account', 'cache: false');
                                }

                            });


                        }
                        else
                        {

                        }
                    }, function(response) {
                        console.log('error',response)
                    });



            }
        }]);

Upvotes: 0

AshishU
AshishU

Reputation: 41

is the alert that you have put printing the correct value?

Based on my understanding I think you set the articleList on ng-change called in one view file. After that you change state and go to another view file where you expect to see the updated articleList value which you set in the previous view. But, I think what may be happening is that when you navigate to the second view your controller might be getting reloaded and your $scope.articleList gets reset. Try printing the value of articleList before and after you change view.

To prevent this you can try using angular services to save the articleList value

Upvotes: 0

Related Questions