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/