Angular offers the flexibility of creating independent Modules that can be reused in various parts of your application. Imagine having a module dedicated to managing lists, which you want to use across your entire application and populate in different ways. Let's explore how this can be achieved:
angular.module('list', []).controller('listController', ListController);
var app = angular.module('myapp', ['list']).controller('appController', AppController);
function AppController() {
this.name = "Misae";
this.fetch = function() {
console.log("fetching");
//change ListController list
//do something else
}
}
function ListController() {
this.list = [1, 2, 3];
this.revert = function() {
this.list.reverse();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="app" ng-app="myapp" ng-controller="appController as App">
<div class="filters">
Name:
<input type="text" ng-model="App.name" />
<button ng-click="App.fetch()">Fetch</button>
</div>
<div class="list" ng-controller="listController as List">
<button ng-click="List.revert()">Revert</button>
<ul>
<li ng-repeat="item in List.list">{{item}}</li>
</ul>
</div>
</div>
When you click the Fetch button, it triggers sending the name (and other filters) to an API using $http
. Upon receiving data, including a list of items for painting, you need to send that list to the List
module for rendering.
The reason for separating the functionality into two modules - one for handling lists and another for API interaction - is to ensure reusability while allowing flexibility for changes in filters and API requests without affecting the core list management features.
Now, the question arises: what is the most efficient way to pass fetched data to the List module? Would utilizing a Service be the best approach?