[英]Angularjs - Binding between controller and view
我在Angularjs視圖中遇到問題。 我不知何故做錯了事,不知道問題出在哪里。 希望有人可以幫助我。
問題是{{user.login}}
(userRepoInfo.html file
)根本沒有從控制器調用,如果我執行console.log,則服務正常。 我肯定在視圖和控制器之間做錯了
I have five files
1) gitHubApiServices.js
2) gitHubApiController.js
3) userRepoInfo.html
4) app.js
5) index.html
以下是gitHubApiServices.js
(function() {
var gitHubApiFactory = function($http) {
var factory = {};
factory.getUserName = function(userName) {
console.log(userName + " " + "This is from Services")
return $http.get("https://api.github.com/users/" + userName);
};
return factory;
};
gitHubApiFactory.$inject = ['$http'];
angular.module('gitHubApp').factory('gitHubApiFactory',gitHubApiFactory);
}());
以下是gitHubApiController.js
(function() {
var gitHubInfoController = function ($scope,gitHubApiFactory) {
$scope.user = null;
$scope.gitHubUser = function(userName) {
gitHubApiFactory.getUserName(userName)
.success(function (data) {
$scope.user = data;
console.log(data);
})
.error(function(data, status, headers, config) {
$log.log(data.error + ' ' + status);
});
}
};
gitHubInfoController.$inject = ['$scope','gitHubApiFactory'];
angular.module('gitHubApp')
.controller('gitHubInfoController', gitHubInfoController);
}());
以下是userRepoInfo.html
<div data-ng-controller="gitHubInfoController">
<h1>Github App</h1>
<input type="text" id="gitUserName" ng-model="gitUser" placeholder="Please enter your GitHub Username">
<a href="#" id="getUserRepo" ng-click="gitHubUser(gitUser)">Get my Repository</a>
{{user.login}}
</div>
下面是app.js
(function() {
var app = angular.module('gitHubApp', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
controller: 'gitHubInfoController',
templateUrl: 'app/views/userRepoInfo.html'
})
.otherwise( { redirectTo: '/' } );
});
}());
以下是index.html
<!doctype html>
<html data-ng-app="gitHubApp">
<head>
<title>Github Repository App</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div data-ng-view></div>
<script src="vendor/angular.js"></script>
<script src="vendor/angular-route.js"></script>
<script src="app/app.js"></script>
<script src="app/controllers/gitHubApiController.js"></script>
<script src="app/services/gitHubApiServices.js"></script>
</body>
</html>
請幫我解決這個問題。 我花了幾個小時,但沒有運氣。
感謝你的付出
我已經在plinkr中使用{{user.login}}而不是{{$scope.user.login}}
嘗試了您的代碼,它可以正常工作。 它返回我的用戶名(或我從GitHub RestFull Api請求的任何其他信息)。
您不應在視圖中使用$scope
。 角度將為您確定適當的范圍,並將其注入以供視圖使用。
看看這個plunkr: http ://plnkr.co/edit/16yyngPoZBgzVvfyWCDq
PS:為簡單起見,我將您的文件夾結構弄平了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.