我对 angularjs 比较陌生。我有一些代码(HTML + JS)允许用户从范围内的数组中添加和删除条目。但是现在我正在为不同的数组大量重复代码。我知道这可以重新考虑,但我不确定角度方法,除了我可能想要使用指令这一事实。非常感谢任何帮助。
的HTML
<div class="control-group" ng-class="{error: form.profile.seeking.$invalid}" ng-controller="SeekingCtrl">
<label class="control-label" for="profile.seeking">Seeking</label>
<div class="controls">
<ul ng-repeat="seeks in profile.seeking">
<li>{{seeks}} <button class="btn" ng-click="removeSeeks()">Remove</button></li>
</ul>
<input type="text" ng-model="newseeks" id="profile.seeking">
<button class="btn" ng-disabled="!newseeks" ng-click="addSeeks()">Add new</button>
</div>
<div class="control-group" ng-class="{error: form.project.offering.$invalid}" ng-controller="OfferingCtrl">
<label class="control-label" for="project.offering">Offering</label>
<div class="controls">
<ul ng-repeat="offer in project.offering">
<li>{{offer}} <button class="btn" ng-click="removeOffer()">Remove</button></li>
</ul>
<input type="text" ng-model="newoffer" id="project.offering">
<button class="btn" ng-disabled="!newoffer" ng-click="addOffer()">Add new</button>
</div>
Javascript
var SeekingCtrl = function($scope) {
$scope.addSeeks = function() {
$scope.profile.seeking = $scope.profile.seeking || [];
$scope.profile.seeking.push($scope.newseeks);
$scope.newseeks = "";
};
$scope.removeSeeks = function() {
$scope.profile.seeking = _.without($scope.profile.seeking, this.seeks);
};
};
var OfferingCtrl = function($scope) {
$scope.addOffer = function() {
$scope.project.offers = $scope.project.offers || [];
$scope.project.offers.push($scope.newoffer);
$scope.newoffer = "";
};
$scope.removeOffer = function() {
$scope.project.offers = _.without($scope.project.offers, this.offer);
};
};