我剛開始學習MEAN堆棧,並試圖從頭構建一個認證頁面(儘管我知道我可以使用開箱即用身份驗證,但我這樣做有一個背景知識),但我覺得有點棘手更新我的導航欄上的文本。 我的index.html
看起來像這樣;如何將數據從ng-view傳遞到位於Agularjs的index.html的navbar
<nav class="navbar navbar-default navbar-fixed-top" ng-controller="HeadController">
<div class = "container-fluid">
<ul class="nav navbar-nav navbar-right">
<li><a href="#">{{user.name}}</a></li>
</ul>
</div>
</nav>
<div class="container" ng-view></div>
我的app.js
看起來像這樣;
var app = angular.module('app',['ngRoute'])
.service("userService", function() {
this.user = {};
this.getUser = function() {
return this.user;
};
this.setUser = function (user) {
this.user = user;
};
})
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/login', {
templateUrl: 'partials/login.html',
controller: 'LoginCtrl as login'
})
.when('/user/profile',{
templateUrl: 'partials/profile.html',
controller: 'ProfileCtrl as profile'
})
.otherwise({
redirectTo: '/login'
});
}]);
app.controller("HeadController", [
'$scope',
'userService',
function ($scope, userService) {
$scope.user = userService.getUser();
}]);
app.controller("LoginCtrl", [
"$location",
"userFactory",
"userService",
function ($location, userFactory, userService) {
var login = this;
login.user = {
username: '',
password: '',
isRemember: true
};
login.login = function() {
userFactory.login(login.user)
.success(function (user) {
userService.setUser(user);
$location.path("/user/profile");
})
.error(function (err) {
console.log(err);
});
};
}]);
終於,我的userFactory.js
看起來像這樣;
function login(user) {
return $http({
url: '/api/login/',
method: "POST",
data: user,
headers: {
'Content-Type': 'application/json'
}
});
}
return{login:login};
每當我登錄,我希望{{user.name}}
被更新,但不會發生。我不知道如何完成這件事。我能做些什麼來做到這一點?
給定您正在開始新的..使用組件和基於組件的路由..它會更容易理解... – harishr
@entre請你能夠友好解釋嗎? –