Prevent Angular.js stripping html formatting out of a json file - angularjs

I'm attempting to iterate through data in a json file using Angular 1. One of the pieces of data contains HTML fieldsets and tabular data. Angular is stripping this out. How can I prevent this?
This is the code I am using for the app:
var app = angular.module( 'myApp', ['ngSanitize'] );
app.controller('crisisCtrl', function($scope, $http) {
$http.get("data.php").then(function(response) {
$scope.mkyData = response.data.records;
});
});
Json file (data.php):
{
"records": [
{
"Card": "3",
"Title": "Blah",
"Content": "<fieldset class=\"table bt-0\"><thead><tr><th>Name</th><th>Role</th><th>Number</th></tr></thead><tbody><tr><td>Bill</td><td> Director</td><td>304 304-3042</td></tr><tr><td>Mary</td><td>Technical</td><td>304 304-3042</td></tr><tr><td>Hannah</td><td>Engineer</td><td>120 104-4042</td></tr></tbody></fielset>"
}
]
}
And within my html file:
<div class="container" ng-app="myApp" ng-controller="crisisCtrl">
<div class="card" ng-repeat="x in myData">
<div class="card-block" ng-bind-html="x.Content"></div>
</div>
</div>
Here's an adjusted fiddle:
http://jsfiddle.net/deCcG/2/

thead and tbody should be used in table. Your browser may accept it, but Angular does not.
Try to just update your $scope.page.content with:
"content":"<fieldset class=\"table bt-0\"><table><thead><tr><th>Name</th><th>Role</th><th>Number</th></tr></thead><tbody><tr><td>Bill Williams</td><td>Widget Director</td><td>+1 304 304-3042</td></tr><tr><td>Mary Barnhill</td><td>Technical</td><td>+44 304 304-3042</td></tr><tr><td>Hannah Kwak</td><td>Engineer</td><td>+44 120 104-4042</td></tr></tbody></table></fieldset>"
Working Fiddle here.
Furthermore, you miss-spelled the closing </fieldset>.

The <fieldset class=\"table bt-0\"> is what is causing the issue, if you add a table element angular will then be able read the HTML being correctly formatted with correct elements and displays correctly
var app = angular.module('myApp', ['ngSanitize']);
app.controller('myCtrl', function($scope) {
$scope.page = {
"title": "Getting Started",
"content": "<fieldset class=\"table bt-0\"><table><thead><tr><th>Name </th><th>Role</th><th>Number</th></tr></thead><tbody><tr><td>Bill Williams</td><td>Widget Director</td><td>+1 304 304-3042</td></tr><tr><td>Mary Barnhill</td><td>Technical</td><td>+44 304 304-3042</td></tr><tr><td>Hannah Kwak</td><td>Engineer</td><td>+44 120 104-4042</td></tr></tbody></table></fieldset>"
}
})

Related

How to display HTML from response as HTML in ng-repeat

I have n number of records coming from backend as HTML in array. I need to display the HTML response as HTML in my view. I tried ng-bind-html , but it takes the last value. Need assistance.
$scope.res= "data": [
{
"jd": "<p>this jd1</p>"
},
{
"jd": "<li>this jd2</li>"
},
{
"jd": "<ul>this jd3</ul>"
},
{
"jd": "<p>this jd4</p>"
}
]
}
Html:
<div ng-repeat="item in res">
<div ng-bind-html ="item.jd">
</div>
You can use $sce.trustAsHtml. See the documentation here.
What you could do is:
Add this line in your controller:
$scope.trustAsHtml = $sce.trustAsHtml;
And update your HTML like this:
<div ng-bind-html ="trustAsHtml(item.jd)">
Note that you should probably start using Angular 6 instead of AngularJS

Access images from local JSON file on the web page in angularjs

Where am i going wrong?
I want to access images from datahl.json file on the web page but unable to access them.Please check the codes and help me.
If possible please refer the solution to plunker editor.
index.html
<div class="col-sm-4" ng-repeat = "hbl in hbls">
<div class="thumbnail" ng-repeat = "h in hbl.data_list"
style="width:100%;">
<img ng-src="{{h.img}}" alt="" style="height:50vh;">
<div class="caption">
<p><strong>{{h.name}}</strong></p>
</div>
</div>
</div>
app.js This is my js codes
var app = angular.module('hostellApp', []);
app.controller('hostellController', function($scope, hblsFactory){
$scope.hbls;
hblsFactory.getHbls().then(function(response){
$scope.hbls = response.data;
});
$scope.sayHello = function(){
console.log("Hello");
}
});
app.factory('hblsFactory', function($http){
function getHbls(){
return $http.get('datahl.json');
}
return {
getHbls: getHbls
}
});
datahl.json This is my local JSON file
`
{
"view_type": 5,
"title": "Hostels By Locality",
"position": 5,
"data_list":
[
{
"img": "https://s3.us-east-2.amazonaws.com/images-city-
teens/IMG_20180526_1139570.8091572935412125.jpg",
"name": "Mahavir Nagar"
},
{
"img": "https://graph.facebook.com/1666751513414902/picture?
type=large",
"name": null
},
{
"img": "https://s3.us-east-2.amazonaws.com/images-city-
teens/cropped1148015742983667713.jpg",
"name": "New Rajiv Gandhi"
},
{
"img": "https://s3.us-east-2.amazonaws.com/images-city-
teens/cropped998427941.jpg",
"name": "Jawahar Nagar"
}
]
}`
The data you get from your JSON file is not an array but an object. This means that you only need one ng-repeat.
Change your first ng-repeat to ng-repeat="h in hbls.data_list"(added an 's' to hbl) and delete your second ng-repeat.
Working plunker: https://plnkr.co/edit/OOd1M1dNFjSB7uaqZZB6?p=preview

Append key value pair to angularjs object

I am getting json output from laravel 5.2 form request validation
My json output is:
{
"title": [
"The title field is required."
],
"description": [
"The description field is required."
],
"address.city": [
"City field is required"
]
}
Appending this output to object
var self = this;
self.error = {
address: {}
};
var onFailure = function (response) {
angular.forEach(response.data, function(value, key) {
self.error[key] = value[0];
});
};
I want to access this error object to my view, for "address.city", I can't access it using "ctrl.error.address.city", rest I can access
How to append object with key containing "." and show it in view?
Here is what you need. But its better not to have (.) in a property name. Instead you can use a underscore(_). Avoid using dot(.) as a chaaracter in property names.
var myApp = angular.module('MyApp', []);
myApp.controller('MyCtrl', function ($scope) {
$scope.foo={};
$scope.foo['hello.There'] = "I'm foo!";
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyApp" ng-controller="MyCtrl">
{{foo["hello.There"]}}<br />
<input type="text" ng-model="foo['hello.There']" />
</div>
if you know the key name then the only way you can access it is by [].
Check the fiddle for more info.
https://jsfiddle.net/9f4mbh1h/1/
You need to change your code to this
in your controller
myApp.controller('MyCtrl', function ($scope) {
$scope.foo={};
$scope.foo "hi";
});
in html
<div ng-app="MyApp" ng-controller="MyCtrl">
<input type="text" ng-model="foo" /> </div>

angularjs dynamic model in directive from json object

I have a json file of objects that store the properties to be used in a directive.
I want to use the json obj model value in the directive, but nothing I am trying is working.
Anyone have any ideas what I am doing wrong / missing? I find this very confusing.
Hope someone can help been trying this for days now!
Edit::
I have a $http service that gets and returns the Json object and I can access the properties fine.
I am specifically trying to use the value of the json obj model property -- "model" : "ticketData.contactname" as the dynamic value of the ng-model.
If I just use the ticketData.contactname obj then it works fine and I can edit the model value, but if I try and use the string from the Json obj then it just prints the string into the input box.
I do not know what to do. I am sure it is something basic I am missing.
Thanks in advance
Json sample:
[
{
"inputsContact" : [
{
"labelName" : "Contact Name",
"placeholder" : "Enter your name",
"model" : "ticketData.contactname",
"type" : "text"
}
}
]
Html sample:
<text-input-comp inputdata="contactName" ng-model="contactModel"> </text-input-comp>
Directive text-input-comp:
.directive('textInputComp', [ '$compile', function($compile){
return {
restrict: 'E',
scope: {
inputData: '=inputdata',
modelData: '=ngModel'
},
templateUrl: '/app/views/partials/components/textInputComp.html'
}
}]);
Directive template sample:
<label> {{ inputData.labelName }} </label>
<input type="text" ng-model="modelData" ng-model-options="{ getterSetter: true }" placeholder="{{ inputData.placeholder }}" />
<div ></div>
Controller sample:
$scope.contactName = $scope.inputData[0].inputsContact[0];
$scope.contactModel = $scope.inputData[0].inputsContact[0].model;
i think u need to get the json file first then do all the manupilation
have a look at this code
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<ul>
<li ng-repeat="x in myData">
{{ x.Name + ', ' + x.Country }}
</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("customers.json").then(function (response) {
$scope.myData = response.data.records;
});
});
</script>
</body>
</html>
What u were missing is this
Just replace the customer.json file with your json and u are good to go
and
1.$http is service responsible for communicating with other file. $http says get file from ‘js/data.json’ and if the operation is a ‘success’ then execute a function holding the ‘data’ which it got automatically from data.json file
to make u understand.
2.A one more line above: [‘$scope’, ‘$http’, function($scope, $http){ … }] is little bit tricky: it takes an array holding two objects one is $scope and other is a service i.e $http. The reason we have this in array is angularJS automatically minifies code which means it removes extra spaces and shorten variable names for faster performance but sometimes this minification causes trouble so we just told controller NOT to minify $scope, $http services and function inside array.

Angular not dynamically updating deferred HTML

I'm trying to build a dynamic site using Angular. I'm trying to simulate delays in loading HTML by using setTimeout with $q.defer. It works if I don't have the timeout, but as soon as I add the timeout the data isn't loaded. It does get populated if I click between different views, so I know it's executing. But Angular doesn't seem to be aware that it's finally available.
I've got an HTML file, with the following:
<div ng-controller="MyCtrl">
<div id='my-content' ng-view></div>
<div id='footer'>
footer here
View 1 View 2
</div>
</div>
Here's view1.html:
<div ng-include="'teasers.html'"></div>
Here's teasers.html:
<div class='column content' ng-repeat="teaser in data.teasers">
<div class='button type-overlay' ng-class="{{ 'button-' + ($index + 1) }}">
<div class='teaser-text'>
<img class='button-background' ng-src='{{ teaser.img_src }}'>
<span class='teaser-text'>{{ teaser.name }}</span>
</div>
</div>
</div>
Here's my app.js:
var app = angular.module('app', [], function($routeProvider, $locationProvider) {
$locationProvider.hashPrefix("!");
$routeProvider.when('/', {
templateUrl: 'view1.html'
});
$routeProvider.when('/view2', {
templateUrl: 'view2.html'
});
});
app.factory('data', function($http, $q) {
return {
fetchTeasers: function () {
var deferred = $q.defer();
setTimeout(function() {
deferred.resolve([
{
"name": "Teaser 1",
"img_src": "SRC"
},
{
"name": "Teaser 2",
"img_src": "SRC"
},
{
"name": "Teaser 3",
"img_src": "SRC"
},
{
"name": "Teaser 4",
"img_src": "SRC"
}
]);
}, 5000);
return deferred.promise;
}
}
});
And here's the controller.js:
function MyCtrl($scope, data) {
$scope.data = {};
$scope.data.teasers = data.fetchTeasers();
}
What do I need to do to get deferred working in Angular?
Instead of window.setTimeout use angular timeout method: $timeout. Be sure to load it via DI.
$timeout(function(){
// all your magic goes here
});
By the way, you could use setTimeout, but then you would need do call $scope.$apply() manually. In fact this is what angular does internally.
$scope.$apply(function(){ // all your magic goes here })
But again, as I said, just use $timeout.
PS. The reason view gets updated after user interaction is the fact that it invokes dirty checking, unfortunately a little bit too late in this case. Using $apply or $timeout will ensure that angular gets notified about the changes when needed.
PPS. Although I've posted an answer to this particular problem, I should mention that you in this case you could use $resource, which is a angular service supporting RESTful APIs with promises. It uses an implementation of deferreds based on $q as well. There's no need to reinvent the wheel, unless you have any good reasons for it.

Resources