免责声明,我是一个棱 Angular 分明的菜鸟。
因此,过去几个小时我一直在尝试做的是通过单击一个按钮来切换我的服务中的身份验证,该按钮应显示用户信息或登录图像,具体取决于身份验证是否正确。它在页面加载时显示正确的信息,但在我单击按钮时不会重新更新 View 。只是为了好玩,我添加了一个绑定(bind)到用户信息用户名的输入字段,以查看绑定(bind)是否有效。我能够按预期实时更新用户名,但我注意到一个奇怪的结果。如果我切换身份验证按钮,则没有任何变化,但当我尝试通过输入框更新用户名时, View 将更新。正在对身份验证进行更改,但由于某种原因没有反射(reflect)出来。
如有任何帮助,我们将不胜感激。
var app = angular.module("appMain", []);
app.service("userInformation", [function() {
this.authentacation = true;
this.username = "user";
this.balance = "10.00";
this.avatar = "http://cdn.akamai.steamstatic.com/steamcommunity/public/images/avatars/81/81322ac9812dad58e9525a010c76bcf4e585d820.jpg";
this.toggleAuthentacation = function() {
this.authentacation = !this.authentacation;
console.log(this.authentacation);
};
}]);
app.controller("headerController", ["$scope", "userInformation", function($scope, userInformation) {
$scope.userInformation = userInformation;
console.log($scope.userInformation);
document.getElementById("btn1").addEventListener("click", function() {
userInformation.authentacation = ! userInformation.authentacation;
$scope.userInformation = userInformation;
console.log($scope.userInformation);
});
}]);
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="css/style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="appMain">
<header ng-controller="headerController">
<img id="logo" src="/img/logo.png">
<div id="userInfo" ng-show="userInformation.authentacation">
<ul>
<li>Hello {{userInformation.username}}!</li>
<li>Balance: ${{userInformation.balance}}</li>
<li><img id="avatar" src="{{userInformation.avatar}}" /></li>
</ul>
</div>
<div id="userInfo" ng-hide="userInformation.authentacation">
<ul>
<li><img src="https://steamcommunity-a.akamaihd.net/public/images/signinthroughsteam/sits_01.png"></li>
</ul>
</div>
<button id="btn1">Button1</button>
<input type="text" ng-model="userInformation.username">
</header>
</body>
</html>
最佳答案
事件处理程序需要与 AngularJS 框架及其摘要循环集成。 ng-click
directive自动执行此操作。
Angular 通过提供自己的事件处理循环来修改正常的 JavaScript 流程。这将 JavaScript 分为经典和 Angular 执行上下文。只有在 Angular 执行上下文中应用的操作才能从 Angular 数据绑定(bind)、异常处理、属性监视等中受益
(source: angularjs.org)
关于javascript - 查看不应该更新的时候,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42610929/