为什么这些变量不在 html 视图中打印

Why aren't these variables printing in html view?

本文关键字:html 视图 打印 变量 为什么      更新时间:2023-09-26

一个AngularJS应用程序有一个名为authenticated2的变量,需要在html视图中访问。 但是该值不会在屏幕上打印出来。

可以对下面的代码进行哪些具体更改,以确保在屏幕上打印出authenticated2的值?

以下是相关的 html:

auth.authenticated2 is: {{ auth.authenticated2 }} <br>
authenticated2 is {{ authenticated2 }} <br>
$scope.authenticated2 is {{ $scope.authenticated2 }} <br>
<div ng-show="auth.authenticated2=='yes'">
    <h1>Show some stuff.</h1>
</div>

就目前而言,加载上述 html 视图时不会打印任何内容。 但是控制器挂接到视图,因为视图中的其他对象是基于控制器中的其他变量加载的。

以下是security.js控制器中的相关内容:

angular.module('secure', ['auth']).controller('secure', function($scope, $http, $sce, auth) {
    $scope.authenticated1 = function() {
        if(auth.authenticated1=='yes'){return true;}
        else{return false;}
    }
    $scope.authenticated2 = function() {
        if(auth.authenticated2=='yes'){return true;}
        else{return false;}
    }
    //bunch of unrelated stuff
    $scope.$on('$viewContentLoaded', function() {
        //bunch of unrelated stuff
    }
});

这是来自auth.js的相关内容:

angular.module('auth', ['ngCookies']).factory('auth', ['$rootScope', '$http', '$location', '$cookies', function($rootScope, $http, $location, $cookies){
    var auth = {
        authenticated1 : $cookies['AUTH1'],
        authenticated2 : $cookies['AUTH2'],
        //bunch of unrelated stuff  
        init : function(homePath, loginPath, logoutPath) {
            //bunch of unrelated stuff
        }
    };
    return auth;
}]);

由于authenticated2是一个函数,因此您必须调用它:

{{ authenticated2() }}

但似乎你可以侥幸将auth(或部分)放在$scope上并直接使用它。 例如在您的控制器中:

$scope.auth = auth;

并在您的 HTML 中:

{{ auth.authenticated2 }}

它与auth.authenticated2(不是函数)和$scope.authenticated2(函数)有点混淆。

由于它是关于在范围内获取身份验证变量,我可以建议您在某些 init 中设置变量 auth。

angular.module('secure', ['auth']).controller('secure', 
function($scope, $http, $sce, auth) {
    init();
    function(){
        //It is good to have an init method if you have some sigin activies
        //before setting every variable else where
        $scope.auth ={};
        auth.getLoginInfo().then(function(res){
            var auth = {};
            auth.authenticated2 = res.authenticated2;
            $scope.auth = auth;
        });
    }
    $scope.authenticated1 = function() {
        if(auth.authenticated1=='yes'){return true;}
        else{return false;}
    }
    $scope.authenticated2 = function() {
        if(auth.authenticated2=='yes'){return true;}
        else{return false;}
    }
    //bunch of unrelated stuff
    $scope.$on('$viewContentLoaded', function() {
        //bunch of unrelated stuff
    }
});

在您的 HTML 中,它与以下内容相同:

auth.authenticated2 is: {{ auth.authenticated2 }} <br>
authenticated2 is {{ authenticated2() }} <br>
<div ng-show="auth.authenticated2=='yes'">
 <h1>Show some stuff.</h1> 
</div>