关于角度的伟大之处在于您可以拥有可在不同地方重复使用的独立模块.假设你有一个模块来绘制,订购和使用列表做很多事情.说这个模块将在您的应用程序周围使用.最后,说你想以不同的方式填充它.这是一个例子:
- 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("feching");
- //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>
现在,当您点击Fetch按钮时,您将使用$http发送名称(以及其他过滤器和内容)到API.然后,您将获得一些数据,包括您要绘制的项目列表.然后,您要将该列表发送到列表模块,以进行绘制.
它必须是这样的,因为您将在不同的地方使用列表模块,它将始终绘制列表,并添加一些功能,如重新排序和反转.虽然过滤器和API连接将更改,但您的列表行为将不会,因此必须有2个不同的模块.
也就是说,提取数据后,将数据发送到列表模块的最佳方式是什么?有服务?
解决方法
您应该使用
Angular components执行此任务.
您应该创建一个组件,该组件将显示列表,并提供一些可以修改列表的操作,并告诉父级更新该值.
- var list = angular.module('listModule',[]);
- list.controller('listCtrl',function() {
- this.reverse = function() {
- this.items = [].concat(this.items).reverse();
- this.onUpdate({ newValue: this.items });
- };
- });
- list.component('list',{
- bindings: {
- items: '<',onUpdate: '&'
- },controller: 'listCtrl',template: '<button ng-click="$ctrl.reverse()">Revert</button><ul><li ng-repeat="item in $ctrl.items">{{ item }}</li></ul>'
- });
这样当您单击“还原”列表组件将反转数组并执行HTML元素的on-update属性中提供的功能.
然后,您可以简单地将您的应用程序设置为依赖于此模块
- var app = angular.module('app',['listModule']);
并使用列表组件
- <list data-items="list" data-on-update="updateList(newValue)"></list>
您可以在the example中看到其余的代码