Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to refactor angularjs controllers with mostly common code
    text
    copied!<p>I'm relatively new to angularjs. I've got some code (HTML + JS) that allows a user to add and remove entries from an in-scope array. Right now however I am massively repeating code for different arrays. I know this can be re-factored but I'm not sure of the angular approach, other than the fact that I'll probably want to use a directive. Any help greatly appreciated.</p> <p><strong>The HTML</strong></p> <pre><code>&lt;div class="control-group" ng-class="{error: form.profile.seeking.$invalid}" ng-controller="SeekingCtrl"&gt; &lt;label class="control-label" for="profile.seeking"&gt;Seeking&lt;/label&gt; &lt;div class="controls"&gt; &lt;ul ng-repeat="seeks in profile.seeking"&gt; &lt;li&gt;{{seeks}} &lt;button class="btn" ng-click="removeSeeks()"&gt;Remove&lt;/button&gt;&lt;/li&gt; &lt;/ul&gt; &lt;input type="text" ng-model="newseeks" id="profile.seeking"&gt; &lt;button class="btn" ng-disabled="!newseeks" ng-click="addSeeks()"&gt;Add new&lt;/button&gt; &lt;/div&gt; </code></pre> <p></p> <pre><code>&lt;div class="control-group" ng-class="{error: form.project.offering.$invalid}" ng-controller="OfferingCtrl"&gt; &lt;label class="control-label" for="project.offering"&gt;Offering&lt;/label&gt; &lt;div class="controls"&gt; &lt;ul ng-repeat="offer in project.offering"&gt; &lt;li&gt;{{offer}} &lt;button class="btn" ng-click="removeOffer()"&gt;Remove&lt;/button&gt;&lt;/li&gt; &lt;/ul&gt; &lt;input type="text" ng-model="newoffer" id="project.offering"&gt; &lt;button class="btn" ng-disabled="!newoffer" ng-click="addOffer()"&gt;Add new&lt;/button&gt; &lt;/div&gt; </code></pre> <p></p> <p><strong>The Javascript</strong></p> <pre><code>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); }; }; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload