我尝试实现$ scope。$ apply()但是我试过的每一种方式都抛出了$ apply的错误已经在进行中。 ng-bind =" controller.data.name是我尝试更新的内容,但它只适用于刷新。我的理解是$ http已经调用$ scope。$ apply(),所以我很难概念化为什么它不起作用。
更新:我遇到的每一份文档都显示此代码应该是正确的,但视图不会更新。
的index.html:
<!doctype html>
<html ng-app="wishingWell">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="/css/normalize.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-route.js"></script>
<script src="https://code.jquery.com/jquery-3.1.1.js" integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA=" crossorigin="anonymous"></script>
<script src="/javascript/app.js"></script>
<title>Wishing Well</title>
</head>
<body>
<nav class="nav" ng-controller="home as controller">
<ul class="navback">
<li>
<a class="active" href="#/">The Well</a>
</li>
<li ng-hide="!authenticated">
<a href="#/profile" >Profile</a>
</li>
<li ng-hide="authenticated">
<a href="#/sign-up">Sign Up</a>
</li>
<li ng-hide="authenticated">
<a href="#/login">Log In</a>
</li>
<li ng-hide="!authenticated">
<a href="" ng-click="controller.logout()">Sign Out</a>
</li>
<li>
<span ng-bind="controller.data.name"></span>
</li>
</ul>
</nav>
<div ng-view></div>
<script src="/javascript/wishAJAX.js"></script>
</body>
</html>
app.js:
var wishingWell = angular.module('wishingWell', [ 'ngRoute' ]);
wishingWell.config(function($routeProvider, $httpProvider) {
$routeProvider.when('/', {
templateUrl : 'home.html',
controller : 'home',
controllerAs: 'controller'
}).when('/login', {
templateUrl : 'login.html',
controller : 'navigation',
controllerAs: 'controller'
}).when('/sign-up', {
templateUrl : 'sign-up.html',
controller : 'register',
controllerAs: 'controller'
}).otherwise('/');
$httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
});
wishingWell.controller('home', function($rootScope, $http, $location) {
var jsonResponse;
var jsonString;
var self = this;
self.data = {};
$http.get('user2').then(function(response) {
jsonString = JSON.stringify(response.data);
jsonResponse = JSON.parse(jsonString);
self.data.name = jsonResponse.msg;
});
self.logout = function() {
$http.post('logout',{}).finally(function() {
$rootScope.authenticated = false;
$location.path("/");
});
}
});