繁体   English   中英

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

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

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

我在用 CSS 隐藏的页面上有一个 div,里面的 .people-data 类是一个无序列表。 这是我的服务:)

我相信我可能需要将我的 jQuery 包装起来,该 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/#!topic/angular/6A3Skwm59Z4

希望能帮助到你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM