【发布时间】:2018-12-30 15:07:28
【问题描述】:
我正在学习一个简单的 Todo Angular 应用程序。用户必须输入用户名并显示来自 API get 调用的待办事项列表。当我将 API 调用保留在 getTodo 函数调用之外并直接启用与 todos 范围变量的 2 向绑定时,我能够显示 todos。但是在 getTodo 函数调用中,当 API 调用成功返回时,todos 范围变量不会保留在 Angular 上下文中。
Main Todo List
<div ng-controller="mainController">
<form name="form1">
<p>Enter Username:<input name="username" type="text" ng-model="username" ng-minlength='4' required/>
<span ng-show="form1.username.$error.minlength">Username has to be atleast 4 chars</span></p>
<div ng-messages="form1.username.$error">
<div ng-message="required" ng-style={color:'purple'}> get todos for test user. type your username to get and add your todos</div>
</div>
<div ng-model="todos">
<!--<a href="#" class="btn btn-default" ng-click="getTodo()">Get Todo</a>-->
<button class="btn btn-default" ng-click="getTodo()">Get Todo</button>
<h3>Todos</h3>
<ul>
<li ng-repeat="todo in todos">
{{ todo.todo }}
</li>
</ul>
</div>
</form>
</div>
// MODULE
var angularApp = angular.module('angularApp',['ngRoute']);
angularApp.config(function ($routeProvider){
$routeProvider
.when('/', {
templateUrl: 'pages/MainTodo.html',
controller: 'mainController'
})
.when('/edittodo', {
templateUrl: 'pages/EditTodo.html',
controller: 'editController'
})
});
angularApp.controller('mainController', ['$scope', '$location', '$log', '$http',
function ($scope, $location, $log, $http) {
//$log.info($location.path());
$scope.username = "test";
$scope.todos = {};
var uname = $scope.username;
var getApiPath = '/api/todos/' + uname;
$scope.getTodo = function() {
$http.get(getApiPath)
.success(function (result) {
$scope.todos = result;
console.log(result);
})
.error(function (data, status) {
console.log(data);
});
};
}]);
angularApp.controller('editController', ['$scope', '$location', '$log', function ($scope, $location, $log) {
//$log.info($location.path());
}]);
【问题讨论】:
-
$scope.username 是否返回值?我相信你的函数被调用了,但在代码中你应该使用 $scope.$parent.username
-
是的,我在成功承诺中添加了 console.log (console.log(uname); 在 console.log(result); 之后,并且两者都显示了数据。
-
(2) [{…}, {…}]0: {id: "5c240eb25928a60004ffb48b", 用户名: "test", todo: "Biking", isDone: false, hasAttachment:假,...}1:{_id:“5c27fb3685734c000476bf22”,用户名:“测试”,待办事项:“发短信”,isDone:假,hasAttachment:假,...}长度:2__proto_:数组(0)app.js :29 测试
-
所以你的方法被调用了?它根本不从服务器返回任何东西?
-
请不要编辑问题中的代码以反映答案;它只会使问题使其他可能正在寻找他们可能遇到的类似问题的人感到困惑,因为他们看不到与他们的代码外观相匹配的损坏状态的代码,并且答案似乎是错误的,因为他们似乎建议改变看起来不正确的东西。
标签: angularjs