Extract data from existing HTML using Angular.js

angular.js is great for complex JavaScript-based web client applications, but I'm also thinking of using it for small, simple JavaScript tasks.

For example, I have a list with some elements:

<ul> <li data-id="1">Foo</li> <li data-id="2">Bar</li> </ul> 

Now I want to add some buttons in the HTML that should filter and / or sort the list after some user input, which should be an easy task.

Is there a way to extract data from existing HTML elements to use with angular.js? The data must be in HTML, so the search engine could also get information that

Edit for clarity:

The end result is that the data from the ul list will be transferred to the model of the controller that processes the list. ( [{id:1, text:"Foo"}, {id:2, text:"Bar"}] )
If I push more objects to the model, the list should display them.
If I applied a filter to the model, it should filter out the li elements.

A better scenario would be similar to this:

 <div ng-model="data"> <ul ng-repeat="object in data | filter:filterCriteria"> <li data-id="1">Foo</li> <li data-id="2">Bar</li> <li data-id="{{object.id}}">{{object.text}}</li> </ul> </div> 
+6
source share
3 answers

Good. There seems to be no Angular.js default application in this case.

0
source

I ran into the same problem in the project I'm working on. My solution was to add data from html to a variable in my angular controller and then hide the original html. This method saves the original list in html for SEO, older browsers and users without javascript. It replaces this angular list with one generated by other users.

A working example using your code is inserted below or you can see it at this link .

I know this is an old question, so my answer may not help the original poster. My solution is aimed at everyone who faces the same problem as us.

 <!doctype html> <html xmlns:ng="http://angularjs.org" id="ng-app"> <head> <script src="http://code.jquery.com/jquery-1.9.0.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script> <script> function Ctrl($scope) { $scope.objects = []; $scope.init = function(){ $("ul.data").hide(); $("ul.data li").each(function(){ var $this = $(this); var newObject = { name: $this.html(), id: $this.attr("data-id") }; $scope.objects.push(newObject); }); }; } </script> </head> <body> <div ng-app> <div ng-controller="Ctrl" ng-init="init()"> <ul> <li ng-repeat="object in objects" data-id="{{object.id}}">{{object.name}}</li> </ul> <ul class="data"> <li data-id="1">Foo</li> <li data-id="2">Bar</li> </ul> </div> </div> </body> </html> 
0
source

If I understand the question correctly, you can simply use the angular.element () scope for the html element in question.

I use this method for a specific interaction that cannot be processed directly from the box using angular.

0
source

All Articles