Insert new html element into every ng-repeat (AngularJS) - javascript

I'm having some trouble figuring out a way to insert a <p> in the DOM in each item of ng-repeat.
I'm doing ng-repeat of this array of objects:
$scope.items = [
{name: "john", paragraph:"<p>hi, im john</p>"},
{name: "rita", paragraph:"<p>hi, im rita</p>"},
{name: "joe", paragraph:"<p>hi, im joe</p>"}
];
then in the html file I have:
<div ng-repeat="item in items">
<br>
<br>
<p>this is the beginning of {{$index}} box</p>
<p>{{item.name}}</p>
{{insertHTML(item.paragraph)}}
<p>this is the end of {{$index}} box</p>
<br>
<br>
</div>
the insert.HTML(str) function is supposed to transform the string on each item.paragraph into an html element.
Here's the function:
$scope.insertHTML = function(str) {
var wrapper = document.createElement('div');
wrapper.innerHTML = str;
};
I created this plunker where you can check the whole code running

Try Directives. See demo here
var app = angular.module('plunker', []);
app.directive('myDir',function(){
return{
link : function(scope,element){
element.append(' <br><br><p>this is the beginning of box</p>');
element.append('<p>'+scope.item.name+'</p>');
element.append(' <p>this is the end of box<br><br><br></p>');
}}
})
app.controller('MainCtrl', function($scope) {
$scope.items = [
{name: "john", paragraph:"<p>hi, im john</p>"},
{name: "rita", paragraph:"<p>hi, im rita</p>"},
{name: "joe", paragraph:"<p>hi, im joe</p>"}
];
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<div ng-repeat="item in items">
<my-dir></my-dir>
</div>
</body>
</html>

You should use Angular's built in ng-bind-html and ngSanitize:
angular.module("demo", ["ngSanitize"]);
angular
.module("demo")
.controller("demoController", ["$scope", "$sce", function($scope, $sce) {
$scope.items = [{
name: "john",
paragraph: $sce.trustAsHtml('<iframe border="0" frameborder="0" allowtransparency="true" width="603" height="465" src="//www.chess.com/emboard?id=3681802"></iframe>')
},
{
name: "rita",
paragraph: "<p>hi, im rita</p>"
},
{
name: "joe",
paragraph: "<p>hi, im joe</p>"
}
];
}])
.red {
background-color: red
}
.blue {
background-color: blue
}
.green {
background-color: green
}
<!DOCTYPE html>
<html ng-app="demo">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body ng-controller="demoController">
<p>hello everyone</p>
<div ng-repeat="item in items">
<br>
<br>
<p>this is the beginning of {{$index}} box</p>
<p>{{item.name}}</p>
<div ng-bind-html="item.paragraph"></div>
<p>this is the end of {{$index}} box</p>
<br>
<br>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.6/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular-sanitize.js"></script>
</body>
</html>

Related

AngularJS: divide parent <div> every n element

I have a javascript array like this, and trying to generate nested <div> with AngularJS.
var arr = ["abc", "def", "ghi", "jkl", "mno", "pqr", "stu"];
I would like to divide with every 3 elements like this.
<div class="parent">
<div class="child">abc</div>
<div class="child">def</div>
<div class="child">ghi</div>
</div>
<div class="parent">
<div class="child">jkl</div>
<div class="child">mno</div>
<div class="child">pqr</div>
</div>
<div class="parent">
<div class="child">stu</div>
</div>
Can I do this?
One way is create a dummy array based on itemsArray.length/maxItems and use that dummy array for an outer ng-repeat...then use limitTo filter for items.
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.maxItems = 3;
$scope.items = ["abc", "def", "ghi", "jkl", "mno", "pqr", "stu"];
$scope.parentArr = new Array(Math.ceil($scope.items.length/$scope.maxItems));
});
.parent{border: 1px solid #ccc; padding:10px}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
<div ng-app="plunker" ng-controller="MainCtrl">
<div class="parent" ng-repeat="par in parentArr track by $index">
<div ng-repeat="item in items |limitTo: maxItems : $index*maxItems">{{item}}</div>
</div>
</div>
Here is the complete code to achieve it in angularJs using ng-repeat
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp">
<div ng-controller="myCtrl">
<div class="parent" ng-repeat="item in chunkArray">
<div class="child" ng-repeat="child in item">{{child}}</div>
</div>
</div>
</div>
<script>
var app = angular.module("myApp", []);
app.controller('myCtrl', function($scope) {
var data = ["abc", "def", "ghi", "jkl", "mno", "pqr", "stu"];
$scope.chunkArray = chunk(data,3);
function chunk(array, size) {
var result = []
for (var i=0;i<array.length;i+=size)
result.push( array.slice(i,i+size) )
return result;
}
});
</script>
</body>
</html>

Why ng-repeat does not work in this AngularJs 1.5.x component

Here is index.html:
<!DOCTYPE html>
<html ng-app="helloall">
<head>
<meta charset="utf-8" />
<title>Hello All</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.6/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<item data="name" ng-repeat="name in names"></item>
</body>
</html>
Here is app.js file:
var app = angular.module('helloall', []);
function componentCtrl(){
var ctrl = this;
ctrl.otherNames = [{last: "John", first: "Doe"}, {last: "Mary", first: "Jane"}];
}
app.controller('MainCtrl', function($scope) {
$scope.names = [{family: "asdf", first: "test"}, {family: "qwerty", first: "test2"}]
});
angular.module('helloall').component('item', {
controller: componentCtrl,
templateUrl: 'item.html',
bindings: {
data: '='
}
});
And here is the item.html:
<tr ng-repeat="name in $ctrl.otherNames">
Name: {{name.last}}
</tr>
<br>
{{$ctrl.data.first}}
{{$ctrl.data.family}}
<br>
And here is the output:
Other Last Name:
test asdf
Other Last Name:
test2 qwerty
I wonder why ng-repeat in the following section does not work.:
<tr ng-repeat="name in $ctrl.otherNames">
Name: {{name.last}}
</tr>
{{name}} or {{name.last}} outputs nothing.
When I do {{$ctrl.otherNames}} then the output shows the content of "otherNames"
Why?
View the issue in Plunkr: https://plnkr.co/edit/X3gKdZUJIVbNcBlgYfkW?p=preview
Changing the tr tags in item.html to div will make it work.
Additionally you can just add table tags around the tr's and then td's.
https://plnkr.co/edit/U0XjMUkixs9s1RsswWVK

ng-change increment and decrement value in ng-repeat loop

I have a code like this:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Welcome to LearnKode - A code learning platform</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
</head>
<body ng-app="changeExample">
<div ng-controller="ExampleController">
<div class="container">
<div class="col-md-3 well">
Are you developer <input type="checkbox" ng-model="isTrue" ng-change="count=count+1" />
Count: {{count}}
<pre>{{isTrue}}</pre>
</div>
</div>
</div>
<script>
var app = angular.module("changeExample", []);
app.controller('ExampleController', ['$scope', function ($scope) {
$scope.isTrue = true;
}]);
</script>
</body>
</html>
In this code when check the checkbox the count will be incremented. Here how to i check if checkbox is ticked, then only incremented, otherwise if untick, it will decremented. Please anyone help.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Welcome to LearnKode - A code learning platform</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
</head>
<body ng-app="changeExample">
<div ng-controller="ExampleController">
<div class="container">
<div class="col-md-3 well">
Are you developer
<input type="checkbox" ng-model="isTrue" ng-change="isTrue ? (count=count+1) :(count=count-1) " />Count: {{count}}
<pre>{{isTrue}}</pre>
</div>
</div>
</div>
<script>
var app = angular.module("changeExample", []);
app.controller('ExampleController', ['$scope',
function($scope) {
$scope.isTrue = false;
}
]);
</script>
</body>
</html>
try changing ng-change .
This will work for you.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Welcome to LearnKode - A code learning platform</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
</head>
<body ng-app="changeExample">
<div ng-controller="ExampleController">
<div class="container">
<div class="col-md-3 well" ng-repeat="Option in OptionList">
Are you {{Option.choice}} <input type="checkbox" ng-model="Option.value" ng-change="UpdateCount(Option)" />
Count: {{Option.count}}
<pre>{{Option.isTrue}}</pre>
</div>
</div>
</div>
<script>
var app = angular.module("changeExample", []);
app.controller('ExampleController', ['$scope', function ($scope) {
$scope.isTrue = false;
$scope.count = 0;
$scope.OptionList = [{
choice: "Developer",
value: false,
count: 0
},{
choice: "Tester",
value: false,
count: 0
},{
choice: "Lead",
value: false,
count: 0
},{
choice: "Architect",
value: false,
count: 0
}
];
$scope.UpdateCount = function(Option){
if(Option.value){
Option.count = Option.count + 1;
}
else {
Option.count = Option.count - 1;
}
}
}]);
</script>
</body>
</html>

How can I access an array inside an object with angular 1.x?

I have this code:
<div class="list" ng-repeat="key in results">
{{key.locations}}
</div>
JSON
[
{
"locations": [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],
"imgs": ["111.png", "222.png"]
}
]
JS
.controller('ListCtrl', function($scope, $http) {
$http.get("js/data.json").success(function(results) {
$scope.results = results;
});
})
I want to loop trough the array 1,2,3...
Any help much appreciated!
Use another ng-repeat, which is nested in the first one:
<div class="list" ng-repeat="key in results">
<div ng-repeat="location in key.locations">
{{location}}
</div>
</div>
If results always has 1 value, just do this:
<div class="list" ng-repeat="location in results[0].locations">
{{location}}
</div>
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
var test = [];
$scope.results = [
{
"locations": [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],
"imgs": ["111.png", "222.png"]
}
]
for (var i=0;i<$scope.results[0].locations.length;i++)
{
test.push($scope.results[0].locations[i]);
}
$scope.result = test;
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.2.x" src="https://code.angularjs.org/1.2.28/angular.js" data-semver="1.2.28"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<div class="list" ng-repeat="location in result">
{{location}}
</div>
</body>
</html>
You can break and create a temp array and then iterate through that array. Please find the snippet. And let me know your findings

My first simple angular app. Objects aren't displaying

My first angular homework and I can't get the objects I make in my typescript file to appear when I try to call them into my html page. I've got to have a little typo somewhere or something, but I've been playing for an hour and I can't find it. Any help is greatly appreciated.
typescript:
namespace myApp{
angular.module("myApp", []);
class MainController {
public animal;
constructor() {
this.animal = [
{ id: 1, breed: "spaniel", foods: ["alpo", "bones", "cats"] },
{ id: 2, breed: "lab", foods: ["fish", "chicken", "cats"] },]
}
}
angular.module("myApp").controller("MainController", MainController);
And _Layout.cshtml
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>#ViewBag.Title</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="container body-content">
#RenderBody()
<hr />
</div>
<div class="container" ng-controller="MainController as vm">
<div class="col-md-6 col-md-6">
<h1>{{animal}}</h1>
<div>ng-repeat= "food in animal.foods"</div>
{{foods}}
</div>
</div>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/angular-route.min.js"></script>
<script src="~/FrontEnd/JS/app.js"></script>
</body>
</html>
Try this one,
<script>
var myApp = angular.module("myApp",[]); // creating new module
myApp.controller("MainController", function($scope){
// initializing animals variable
$scope.animals = [
{ id: 1, breed: "spaniel", foods: ["alpo", "bones", "cats"] },
{ id: 2, breed: "lab", foods: ["fish", "chicken", "cats"] }];
});
</script>
And your html should be,
<div class="container" ng-controller="MainController">
<div class="col-md-6 col-md-6">
<h1>Animals</h1>
<!-- Loop your animals variable-->
<div ng-repeat="animal in animals">
<h1>{{animal.id}}</h1>
<!-- Loop animal's food-->
<p ng-repeat="food in animal.foods"></p>
</div>
</div>
</div>
Please feel free to ask any doubt in this one.

Categories