如何创建一个数据的独立作用域和应用过滤器? angularjs
如何创建一个数据的独立作用域和应用过滤器? angularjs
我正在练习AngularJS,并尝试创建一个可重用的组件,
到目前为止,我使用指令方法创建了它,我有一个疑问:
我如何将数据集从json调用分离出来?($http.get)
我如何用输入文本过滤当前控件?
var app = angular.module("app", []); app.directive('list', function() { return { restrict: 'E', scope: { list: '=set' }, replace: true, controller: function() {}, controllerAs: 'ctrl', bindToController: true, template: layout } }); // template (html) var layout = ''+ ''+ '
- '+
'
- ' + ''+ ' '+ '
ul { list-style-type:none; margin:0px; padding:0px; } ul > li { background-color:SkyBlue; width:200px; padding:5px 10px; margin-bottom:5px; } input[type="text"] { width:220px; height: 20px }
列表1
列表2
问题的原因是需要从API获取用户数据,并根据特定条件对数据进行筛选。解决方法是创建一个服务来获取数据,并在指令中注入该服务。然后在链接函数中将结果保存在一个变量中,并使用过滤器对列表进行筛选。
首先,创建一个名为userService的服务,该服务使用$http服务从API获取用户数据。getUser函数返回一个promise对象,该对象在获取到数据后将返回结果列表。
然后,在指令中注入userService服务,并在链接函数中使用该服务获取用户数据。将结果保存在一个名为users的空数组中。
接下来,可以使用过滤器来对列表进行筛选。可以参考以下链接中的示例代码来实现过滤功能。
最后,可以通过ng-repeat指令遍历users数组,并根据筛选条件动态显示li元素。
以下是完整的代码示例:
var app = angular.module("app", []); app.service('userService', function($http) { this.getUser = function() { return $http.get('https://randomuser.me/api/').then(function(list) { return list.data.results; }); } }); app.directive('list', function(userService) { return { restrict: 'E', scope: {}, replace: true, template: layout, link: function (scope) { scope.users = []; userService.getUser().then(function(users) { scope.users.push({name: users[0].name.first}); }); } } }); var layout = ''+ ''+ '';'+ '
- ' + ''+ '
'+ '
希望这篇文章对你有帮助!