javascript - 为什么这些变量没有在 html View 中打印?

标签 javascript angularjs

AngularJS 应用程序有一个名为 authenticated2 的变量,需要在 html View 中访问该变量。但该值没有打印在屏幕上。

可以对下面的代码进行哪些具体更改,以确保 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 View 时不会打印任何内容。但是 Controller 连接到 View ,因为 View 中的其他对象是根据 Controller 中的其他变量加载的。

这是 security.js Controller 中的相关内容:

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 上并直接使用它。例如在您的 Controller 中:

$scope.auth = auth;

并在您的 HTML 中:

{{ auth.authenticated2 }}

这与 auth.authenticated2 (不是函数)和 $scope.authenticated2 (函数)有点令人困惑。

关于javascript - 为什么这些变量没有在 html View 中打印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35006453/

相关文章:

javascript - Bootstrap Accordion 在悬停时打开

javascript - 性能:jQuery remove() 与 JavaScript removeChild()

angularjs - 如何确定给定 div 中的某些内容是否具有焦点?

javascript - Angular-Formly:隐藏/禁用服务中的字段

javascript - 在某个 div 中查找元素并使用 jQuery 输出它们各自的文本

javascript - 如何动态地从多个复选框(jquery)获取值并将其复制到文本区域?

javascript - Node.js 在包含的 js 文件中快速渲染

javascript - 如何在angularjs中的两个应用程序之间共享数组

javascript - AngularJs 和 Bootstrap 按钮在预输入中设置值

javascript - 过滤特定的多个表达式 Angular js