如何在Angular.js中编写指令来抓取dom中的数据

How to write a directive in Angular.js to scrape dom for data

本文关键字:抓取 dom 数据 指令 Angular js      更新时间:2023-09-26

我是Angular.js的noob,需要帮助解决一个小问题。我工作的CMS没有服务&不会输出JSON。我唯一的选择是从dom获取数据。我知道这并不理想,在一个完美的世界里,情况会有所不同,但事实并非如此。

我在页面上用CSS隐藏了一个div,其中的.peoples类数据是一个无序列表。这是我的服务:)

我想我可能需要把我的jQuery包装成一个"指令",它正在为数据抓取dom,但我不知道怎么做。把这个jQuery放在控制器里感觉不对。

也许我甚至不需要jQuery来获取这些数据。。Angular能做这样的事情吗?

var angularApp = angular.module('angularApp', []);
angularApp.controller('PeopleCtrl', ['$scope', function PeopleCtrl($scope) {
$scope.people = [];
    // don't want this in controller.. scraping dom for data
    // a directive?? how and where does it go?
    $('.people-data li').each(function(){
      $scope.people.push({ 
          name: $(this).find('.name').text(), 
          email: $(this).find('.email').text() 
      });
    });
} ]);

这是Plunk:http://plnkr.co/edit/kUqL9f?p=info

我用这里的指令制作了一个新的Plunk:http://plnkr.co/edit/Q9FLIyWSzfm77SbvyBys?p=info

基本上,你需要添加:

angularApp.directive('domScraper', function() {
  return {
    restrict: "A",
    link: function(scope, element, attr) {
      scope.people = [];
      $('.people-data li').each(function() {
        scope.people.push({
          name: $(this).find('.name').text(),
          email: $(this).find('.email').text()
        });
      });
    }
  }
});

然后,您只需要将属性dom scraper添加到您设置控制器的元素中。

<div ng-app="angularApp" ng-controller="PeopleCtrl" dom-scraper>

我在你的控制器中添加了一个console.log,向你表明指令和控制器共享相同的作用域,因为我不知道你想对数据做什么。

在你的index.html中,我还切换了jquery和angular。Angular使用的是jQuery的轻量级版本,除非您在Angular库之前需要一个jQuery库。由于您需要jQuery,所以最好将其放在前面。你可以在那里谈论它:https://groups.google.com/forum/#!主题/角度/6A3Skwm59Z4

希望能有所帮助。