免責聲明,我是一個角度noob。查看不更新時它應該
所以我一直在嘗試做的過去幾個小時是切換我的服務中的身份驗證與點擊一個按鈕,應該顯示用戶信息或簽名圖像取決於如果驗證是真實的。它在頁面加載時顯示正確的信息,但當點擊按鈕時不會重新更新視圖。爲了好玩,我添加了一個綁定到用戶信息用戶名的輸入字段,以查看綁定是否正常工作。我能夠按預期更新用戶名,但我注意到了一個奇怪的結果。如果我切換身份驗證按鈕,則不會更改,但當我嘗試通過輸入框更新用戶名時,視圖會更新。正在對認證進行更改,但由於某種原因沒有反映出來。
任何幫助,將不勝感激。
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>
您的按鈕是不是現在做任何事情。這只是一個普通的ol按鈕。你需要用'ng-click'將它連接到'toggleAuthentacation'函數。 – Ladmerc
這個按鈕實際上是更新值並且在headerController中被分配了一個角色。我已檢查它是否與console.log – AllAnimals
@Ladmerc一起進一步調查這是問題!我添加了一個函數給我用ng-click調用的控制器,它立即更新了視圖。你是一個拯救生命的人! – AllAnimals