$ scope变量未在使用$ state呈现的视图上更新

时间:2017-03-02 16:08:22

标签: angularjs

以下是app.js文件包含myApp模块。我面临的问题是$ scope变量未在使用$ state呈现的视图文件上更新。 我从一个使用$ state.go语句渲染的视图文件中调用ng-change事件上的showArticles函数。用户登录后呈现此视图。下面给出了所有代码快照。在AJAX成功响应后,同样面临相同的问题$范围未在视图文件上更新。

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)
                        });



                }
            }]);

从帐户视图调用ng-change事件调用showArticles函数:

<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>

如果我在代码中遗漏了任何内容,请告诉我。我是棱角分明的新手,面对一些我不知道的问题

2 个答案:

答案 0 :(得分:0)

是您打印正确值的警告吗?

根据我的理解,我认为你在一个视图文件中设置了关于ng-change的articleList。之后,您将更改状态并转到另一个视图文件,您希望在该文件中看到您在上一个视图中设置的更新的articleList值。但是,我认为可能发生的情况是,当您导航到第二个视图时,您的控制器可能会重新加载并且$ scope.articleList会重置。尝试在更改视图之前和之后打印articleList的值。

为了防止这种情况,您可以尝试使用角度服务来保存articleList值

答案 1 :(得分:0)

好的,我理解你的问题。每次调用视图时,$ scope变量都会重置。因此,你没有看到任何价值。您必须保存该值,然后在加载视图时检索它。我已在下面更新了您的代码,请尝试让我知道它是否有效

解决方案1: 再创建一个工厂:

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

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

然后在您的控制器中包含上述服务并保存articleList,当您转到新视图时,使用'persistService'初始化您的articleList,如下所示: / p>

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)
                    });



            }
        }]);

如果这有帮助,请告诉我!

编辑:: 解决方案2: 还有另一种方法可以通过更改控制器代码来实现相同的目标。见下面的代码:

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)
                    });



            }
        }]);