我正在构建一个应用程序,用户可以将项目添加到列表中,为了学习,我决定使用Angular(我非常新)。到目前为止,我已经能够成功地将单个项目添加到该列表中而没有任何问题。不幸的是,每当我尝试在没有页面刷新的情况下添加多个时,我就会收到错误 - 特别是"未定义不是函数。"
我花了更多时间考虑尝试解决这个问题,我希望那里的专家可以帮助我。这就是我到目前为止所拥有的:
控制器:
angular.module('streakApp')
.controller('StreakController', function($scope) {
// Removed REST code since it isn't relevant
$scope.streaks = Streak.query();
// Get user info and use it for making new streaks
var userInfo = User.query(function() {
var user = userInfo[0];
var userName = user.username;
$scope.newStreak = new Streak({
'user': userName
});
});
})
.controller('FormController', function($scope) {
// Works for single items, not for multiple items
$scope.addStreak = function(activity) {
$scope.streaks.push(activity);
$scope.newStreak = {};
};
});
查看:
<div class="streaks" ng-controller="FormController as formCtrl">
<form name="streakForm" novalidate >
<fieldset>
<legend>Add an activity</legend>
<input ng-model="newStreak.activity" placeholder="Activity" required />
<input ng-model="newStreak.start" placeholder="Start" type="date" required />
<input ng-model="newStreak.current_streak" placeholder="Current streak" type="number" min="0" required />
<input ng-model="newStreak.notes" placeholder="Notes" />
<button type="submit" ng-click="addStreak(newStreak)">Add</button>
</fieldset>
</form>
<h4>Current streaks: {{ streaks.length }}</h4>
<div ng-show="newStreak.activity">
<hr>
<h3>{{ newStreak.activity }}</h3>
<h4>Current streak: {{ newStreak.current_streak }}</h4>
<p>Start: {{ newStreak.start | date }}</p>
<p>Notes: {{ newStreak.notes }}</p>
<hr>
</div>
<div ng-repeat="user_streak in streaks">
<!-- Removed most of this for simplicity -->
<h3>{{ user_streak.fields }}</h3>
</div>
</div>
答案 0 :(得分:1)
你也可以发布StreakController的html吗?你的解决方案在这个小提琴中运行良好: http://jsfiddle.net/zf9y0yyg/1/
.controller('FormController', function($scope) {
$scope.streaks = [];
// Works for single items, not for multiple items
$scope.addStreak = function(activity) {
$scope.streaks.push(activity);
$scope.newStreak = {};
};
});
每个控制器中的$ scope注入是不同的,因此你必须定义&#34;条纹&#34;在FormController中。
答案 1 :(得分:0)
你的问题来自:
.controller('FormController', function($scope) {
// Works for single items, not for multiple items
$scope.addStreak = function(activity) {
$scope.streaks.push(activity);
^^^^^^
// Streaks is initialized in another controller (StreakController)
// therefore, depending of when is instantiated StreakController,
// you can have an error or not
$scope.newStreak = {};
};
});
更好的设计是实施StreakService ,并在您需要的控制器中注入该服务。当然,在FormController中初始化$scope.streaks
会使您的代码正常工作,但这不是 表单 控制器的责任初始化这些数据。
答案 2 :(得分:0)
我认为FormController
是StreakController
的嵌套控制器,因此它们共享相同的范围。
如果它适用于单个对象,它应该适用于多个对象,问题是你不能只使用push
将一个对象数组推到条纹上,你可以for loop
数组并添加它们单独或使用push.apply技巧。我认为Undefined is not a function.
的原因是因为Stack.query()返回一个元素而不是一个元素数组,因此$scope.streaks
上不存在方法push。