different elemens with ng-repeat - angularjs

By AJAX I get JSON:
data : [
{
"type":"h2",
"PCDATA":"Title"
},
{
"type":"p",
"PCDATA":"First paragraph."
},
{
"type":"li",
"PCDATA":"list node"
},
{
"type":"p",
"PCDATA":"First paragraph."
}
]
and now I need to generate such HTML:
<h2>Title</h2>
<p>First paragraph.</p>
<ul>
<li>list node</li>
</ul>
<p>First paragraph.</p>
Can I do it using ng-repeat directive? How can I generate different HTML elements using one ng-repeat loop?

I don't think you can just use ng-repeat because I don't think something like <{{elem.type}}>{{elem.PCDATA}}</{{elem.type}}> inside ng-repeat would work.
Here's a fiddle for how to do it in controller: http://jsfiddle.net/terebentina/H3vQ9/3/
I simulated the ajax call with $timeout.
However, note that this is at the border of good practice - you shouldn't manipulate html inside your controller but in this case you could argue that you're manipulating data.
A better way to do it would be with a directive that would loop over your data, similar with how I did it in my example

Related

Is there a way to get transform with template to html?

I am using bootbox, I need display product information in it. The product information is returned as json with rest call. I am thinking using a template, and transform from the json to html. I need ng-repeat etc, in the template. The idea way is I can call template and get a html result.
But it seems angularjs $compile need bind to element to render. any idea?
I think you can use ng-include:
var app = angular.module('myApp', []);
app.controller('productCtrl', function($scope) {
$scope.productInfos = [];
});
Use ng-include (You have to the adjust the path depending the location of your template)
<div ng-app="myApp" ng-controller="productCtrl">
<div ng-include="'product-information.html'"></div>
</div>
You can do ng-repeat in product-information.html:
<div ng-repeat= "info in productInfos"> {{ info.prop1 }}</div>

ng-repeat with ng-include not working

I am trying to use an ng-repeat that includes an ng-include. The problem is that the first element in the ng-repeat is just the ng-include template with none of the data from the ng-repeat filled in. Is there a way I can somehow bind the template from the ng-include so it works on the first ng-repeat?
<div ng-repeat="item in items">
<div ng-include src="'views/template.html'"></div>
</div>
For example, if my ng-repeat contains 10 items, then the first item that is rendered will just be the empty template. Items 2-10 WILL be rendered as they should be. What am I doing wrong?
First make sure that the data that is contained in the first index of items actually has the data that you want.
One possible solution to your problem would be to simply not show the first index of the ng-repeat:
<div ng-repeat="item in items" ng-show="!$first">
<div ng-include src="'views/template.html'"></div>
</div>
This may not actually tackle the root of your problem, but it may still get your application working a bit more like what you expect.
Another possible solution:
<div ng-repeat="item in items" ng-include="'views/template.html'"></div>
see example here:
http://plnkr.co/edit/Yvd73HiFS8dXvpvpEeFu?p=preview
One more possible fix just for good measure:
Use a component:
html:
<div ng-repeat="item in items">
<my-include></my-include>
</div>
js:
angular.module("app").directive("myInclude", function() {
return {
restrict: "E",
templateUrl: "/views/template.html"
}
})
I ran into the same problem, and finally figured out that the first element has not been fetched and compiled in time for the first ng-repeat iteration. Using $templateCache will fix the problem.
You can cache your template in a script tag:
<script type="text/ng-template" id="templateId.html">
<p>This is the content of the template</p>
</script>
Or in your app's run function:
angular.module("app").run(function($http, $templateCache) {
$http.get("/views/template.html", { cache: $templateCache });
});
You can also use $templateCache inside your directive, although it's a bit harder to setup. If your templates are dynamic, I would recommend creating a template cache service. This SO question has some good examples of template caching inside a directive and a service:
Using $http and $templateCache from within a directive doesn't return results
Using a directive worked for me: https://stackoverflow.com/a/24673257/188926
In your case:
1) define a directive:
angular.module('myApp')
.directive('mytemplate', function() {
return {
templateUrl: 'views/template.html'
};
});
2) use your new directive:
<mytemplate />
... or if you're concerned about HTML validation:
<div mytemplate></div>

How to reverse an array in angular js without creating a filter

I am having an array in controller as follows
function FooController($scope) {
$scope.items = ["a","b","c"];
}
I used ng-repeat to show the data in items,
<div ng-app>
<div ng-controller="FooController">
<ul ng-repeat="item in items">
<li>{{item}}</li>
</ul>
</div>
</div>
I got the result as a,b,c order. I want to show it in reverse order. that means c,b,a without changing its order in the controller or without creating a filter. How to do that?
Check this link
I faced the same problem, but with an array of objects. This quick solution worked for me, but using the filter is still the best practice.
<li data-ng-repeat="item in data.slice().reverse()">
...
</li>
http://bootply.com/SgVBZvZ708
In order to avoid the writting of a custom filter, I suggest you to use this syntax :
<ul ng-repeat="item in items | orderBy:'-toString()'">
The documentation assume you sort an array of Objects but in your case there are just plain strings.
Wrap the strings in objects and use orderBy or create a new filter:
angular.module("app",[])
.filter("reverse", function(){
return function(items){
return items.slice().reverse(); // Create a copy of the array and reverse the order of the items
};
});
And use it like this:
<ul ng-repeat="item in items|reverse">
Updated fiddle (I've also updated the ng-app directive so it's passed the "app" module.)

Where to put menu when using angular-snap?

I'm using snap.js with AngularJS using the angular-snap.js directive.
https://github.com/jtrussell/angular-snap.js
I'm also using Andy Joslin's angular-mobile-nav.
I'm wondering where I should store the code for the menu:
<snap-drawer>
<p>I'm a drawer! Where do I go in the angular code?</p>
</snap-drawer>
Because this isn't a unique page within the angular-mobile-nav, I'm currently putting the on every page and just using a directive that contains all my menu code/html.
Seems like this could be inefficient as it is loading a new directive on each page, right? Any idea on how to do this better?
Thanks!
So this is what I've done (I also use angular-mobile-nav and angular-snap.js).
This is my HTML Code
<body ng-app="MyApp">
<div snap-drawer>
<ul class="list">
<li ng-repeat="item in sidebar.items" ng-i18next="{{item.name}}" ng-tap="snapper.close();go(item.link)"></li>
</ul>
</div>
<div id="container" snap-content snap-options="snapOpts">
<div mobile-view=""></div>
</div>
</body>
please note that go() is the function to change the page and that I'm using ng-i18next to translate my items. Also ng-tap is a directive which listens for touch events instead of mouse events. With Angular >1.1.5 there's a mobile module, so my ng-tap directive won't be needed anymore.
And by using $rootScope I can put items in the sidebar:
$rootScope.sidebar = {
items: [
{
name: 'item_one',
link: 'page_one'
},
...
]
};
So if you want to change the items in the sidebar, simply override $rootScope.sidebar (not $scope.sidebar) in your controller ;)
If you don't like two animations happen at the same time, you could write a function, which waits for the sidebar to close and then change the page. It could look like this:
$rootScope.waitThenGoTo = function (page, time) {
time = time || 200;
$timeout(function () {
$navigate.go(page);
}, time);
};
If you have still question, please comment. I'll try to update this answer as soon as possible.

AngularJs - Access to DOM element inside ng-repeat

I have the next template:
<div ng-repeat="friend in friends | filter:filterFriendsHandler">
{{friend.name}}
</div>
and in my controller i have:
$scope.filterFriendsHandler = function(friend){
//HERE I WANT TO ACCESS TO FRIEND DOM ELEMENT; to do something like this:
//$(friendElement).text('foo');
}
Thanks
I'm going to answer the specific question here, yes I understand this isn't the "angular" way of doing things. If you want to do things the "correct" way, then don't do this, use a directive. There, disclaimers aside, here's how to do it:
Basically, what you want to do is give the DOM element an ID based on the $index or a unique value in your ng-repeat object. Here, I'll just use $index.
<div ng-repeat="friend in friends" id="friend_{{$index}}" ng-bind-html="doSomethingBadToTheDom('friend_' + $index)">
{{friend.title}}
</div>
Then, inside your controller, just query the DOM for the element with that ID:
$scope.doSomethingBadToTheDom = function(ele_id) {
var element = document.getElementById(ele_id);
element.innerHTML = "I'm abusing angular";
}
We're using ng-bind-html here because the DOM element will exist when your controller function executes, in the case of something like ng-init, it won't.
Again, this goes against everything angular stands for, so if you're trying to follow angular best practices, don't do this.
I've run into situations where the technique is useful though, especially when dealing with non-angular libraries, or those times when the "angular way" is more trouble than it's worth.
You need to use a directive for that
<div ng-app="test-app" ng-controller="MyController">
<div ng-repeat="friend in friends" nop>
{{friend.title}}
</div>
</div>
JS
app.directive('nop', function(){
return {
link: function(scope, elm){
console.log('eee', elm, arguments);
elm.css('color', 'red');
}
}
});
demo: Fiddle

Resources