Show HTML from JSON with Angular - javascript

I'm new with Angular, and i am making an application with ionic. I can't show HTML from JSON in my view.
I searched previous questions but still doesn't work. The html code is written as text..
My code
HTML
<div ng-bind-html="bindHTML"></div>
Json
"usuarios": [
{
"nombre": "Name 1",
"description":"<p>Some HTML</p><p>More HTML</p>",
"id": 0
},
{
"nombre": "Name 2",
"description":"<p>Some HTML</p><p>More HTML</p>",
"id": 1
}
]
Controller
.controller('UserCtrl', ['$scope', '$http', '$state', function($scope, $http, $state) {
$http.get('js/data.json')
.success(function(data){
$scope.data = data.usuarios[$state.params.id];
$scope.bindHTML = $sce.trustAsHtml(data.description);
});
}])
Thanks.

I implemented a plunker to illustrate how this works. The only thing I didn't include is the ui.router $state stuff you are doing.
Controller
app.controller('MainCtrl', function($scope, $http, $sce) {
$http.get('data.json').success(function(data){
$scope.data = $sce.trustAsHtml(data.usuarios[0].descripcion);
});
});
View
<body ng-app="plunker" ng-controller="MainCtrl">
<p ng-bind-html="data"></p>
</body>
I'm not sure why yours wouldn't be working if you tried what was suggested in the thread that was marked as duplicate. That would leave me to believe it has something to do with the $state dependency, but hard to tell with out seeing your full app.

Related

Information doesn't refresh after clicking on link in AngularJS. I've got {{ value }} but not the data

I have an Angular app that takes information from few JSON files.
The first JSON file contains data about cities and managers. Like this:
[
{
"link" : "veliky_novgorod",
"city" : "Великий Новгород",
"manager" : "mr. Sminth",
},
{
"link" : "magnitogorsk",
"city" : "Магнитогорск",
"manager" : "mr. Young",
},...
I use it in order to create a page for every city.
My urls look like this: ...index.html#/cities/veliky_novgorod/, ...index.html#/cities/biisk/, ...index.html#/cities/biisk/mobile/, etc.
Everything works fine, but when I try to go from one page to another information from the other JSON (scopes) doesn't load. After changing page I've always got {{ value }}
But when I make refresh manually, everything is going back to normal.
In other words, how can I reload new page after clicking on link. I tried to use window.location.reload() But it doesn't work.
<li ng-repeat="city in cities">
{{city.manager}}
</li>
My module and controller below:
var curryApp = angular.module('CurryApp', [
'ngRoute',
'curryControllers'
]);
curryApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'link_list.html',
controller: 'CurryListCtrl'
}).
when('/cities/:cityId/', {
templateUrl: 'template-total.html',
controller: 'CurryDetailCtrl'
}).
when('/cities/:cityId/mobile/', {
templateUrl: 'template-mobile.html',
controller: 'CurryMobileCtrl'
}).
otherwise({
redirectTo: '/'
});
}]);
That's my controller:
var curryControllers = angular.module('curryControllers', []);
curryControllers.controller('CurryListCtrl', ['$scope', '$http', function($scope, $http) {
$http.get('cities.json').success(function(data) {
$scope.cities = data;
});
}]);
curryControllers.controller('CurryDetailCtrl', ['$scope', '$routeParams', '$http', '$route',
function($scope, $routeParams, $http, $route) {
$scope.reloadRoute = function(){window.location.reload();}
$scope.cityId = $routeParams.cityId;
$http.get('cities.json').success(function(data) {
$scope.cities = data;
$http.get('paidbc.json').success(function(data2) {
$scope.paidBc = data2;
$scope.isActive = function(item) {
return item.link === $scope.cityId;
};
});
});
}]);
curryControllers.controller('CurryMobileCtrl', ['$scope', '$routeParams',
function($scope, $routeParams) {
$scope.cityId = $routeParams.cityId;
}]);
It seems that is an error related with the href attribute. According to docs:
The wrong way to write it:
link1
The correct way to write it:
<a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
In your case, use:
<a ng-href="#/cities/{{city.link}}" ng-click="reloadRoute()">{{city.manager}}</a>
instead of using only href.

Passing data in between controller without help of url?

I am creating two page webapp using AngularJS.
my Json file is:
{
"data": [
{ "name": "bhav",
"id": 123
},
{"name": "bhavi",
"id": 1234
},
{"name": "bhavk",
"id": 1235
}
]
}
my app.js(Routing file is):
myApp = angular.module('myApp', ['slickCarousel',
'ngRoute',
'myAppControllers',
'myAppServices','swipeLi'
]);
myApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'partials/home-page.html',
controller: 'ProfileListCtrl',
}).
when('/profile/:typeofprofile', {
templateUrl: 'partials/profile-detail.html',
controller: 'ProfileDetailCtrl'
})
}]);
and my 1st page(home-page.html) is in given formate:
<div ng-repeat="data in data">
{{data.name}}
</div>
and on 2nd page(profile-details.html)
I want that id number of that profile considering I am using http.get request to pull data from Json file in controllers.
so please help me to fetch the id or name of clicked profile without passing through URL .
Note: I already look through ui-route link: Angular ui router passing data between states without URL but I didnt get that.
As you stated in the comments, you want to use $state.go() to pass your data.Using $state.go() to pass params is pretty simple as well. You need to inject ui.router in your application. I have created 2 partial views to show the passing of params where the params are passed from header.html to side.html.
Your JS will be something like below:
var app = angular.module('nested', ['ui.router']);
app.config(function($stateProvider,$locationProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/");
$stateProvider.state('top', {
url: "",
templateUrl: "header.html",
controller: 'topCtrl'
})
.state('top.side', {
url: '/app/:obj/:name',
templateUrl: "side.html",
controller: 'filterCtrl'
})
});
app.controller('topCtrl', function($scope,$state) {
$scope.goItem = function(){
$state.go('top.side',{obj:441,name:'alex'});
};
});
app.controller('filterCtrl', function($scope,$state) {
console.log(JSON.stringify($state.params));
$scope.params = $state.params;
});
Here is the working PLUNKER where you will find what you need to do regarding the views, controller and script:
http://plnkr.co/edit/M1QEYrmNcwTeFd6FtC4t?p=preview
I have provided the methods to pass $stateParams using both ui-sref and $state.go(). However, if you want to share the data among all the controllers. see my answer in this question:
Share Data in AngularJs

AngularJS http.get() accessing json breaks controller

I'm new to AngularJS and have been trying to parse a json using the $http method. I made a test $scope.test = "working"; variable, which works fine. After putting in my $http method code it stops working and the $http method isn't working either. Here is my json:
{
"programmes":[
{
"#attributes":{
"id":"1"
},
"name":"Arrow",
"imagepath":"..\/img\/arrow.jpg"
},
{
"#attributes":{
"id":"2"
},
"name":"Fargo",
"imagepath":"..\/img\/fargo.jpg"
},
{
"#attributes":{
"id":"3"
},
"name":"You, me and the Apocalypse",
"imagepath":"..\/img\/youme.jpg"
},
{
"#attributes":{
"id":"4"
},
"name":"Heat",
"imagepath":"..\/img\/heat.jpg"
},
{
"#attributes":{
"id":"5"
},
"name":"The Thick of It",
"imagepath":"..\/img\/thick.jpg"
}
]
}
and here is my controller file:
app.controller('MainController', ['$scope', function($scope) {
$scope.test = "works";
$http.get("../../jsons/programmes.json").success(function(response) {$scope.programmes = response.programmes;});
}]);
and finally, my html:
<ul>
<li ng-repeat="x in programmes">
{{ x.name }}
</li>
</ul>
<p>{{test}}</p>
so with the $http.get() in the controller, {{test}} shows up literally, but when I remove it, it shows 'works'. The ng-repeat ul doesn't work at all. What am I doing wrong?
You need to inject the $http angular service in your controller.
You can take a look at your browser console. Generally it gives you a hint on what you missed.
app.controller('MainController', ['$scope', '$http', function ($scope, $http) {
You're seeing the angular expression {{test}} because your missing dependency breaks your controller code.

Angular factory undefined in controller

I am working on a very simple factory to be used inside an angular controller. The problem is that the factory doesn't seem to be getting picked up inside the controller. The console.log returns undefined and I can't seem to figure out why.
var app = angular.module('App', ['ngRoute', 'ngTouch']);
app.controller('AppController', [
'$scope',
'$rootScope',
'myFactory',
function($scope, $routeParams, myFactory) {
console.log(myFactory)
}]);
app.factory('myFactory', function() {
return 'test';
});
The problem is that your controller is is injecting $rootScope and then you change it to $routeParams in the function. Have a look at this fiddle http://jsfiddle.net/wkqajL2x/6/ where I have removed those two attributes. It then works fine.
var app = angular.module('App', []);
app.controller('AppController', [
'$scope',
'myFactory',
function($scope, myFactory) {
console.log(myFactory)
}]);
app.factory('myFactory', function() {
return 'test';
});
so you just need to decide which one out of those you really want to use.

Angular in Jekyll/Github pages blog - blog post routing

I'm trying to incorporate Angular into my Jekyll/Github Pages blog. So far I've been able to set up the basic pages ("About", "Projects", and a list of posts), but the links for each post route to a non-angular page. I know I haven't set up the routes and partial quite right but am having trouble debugging. Any suggestions? Here's my code:
app.js:
'use strict';
var app = angular.module('myBlog', [
'ngRoute',
'ngResource',
'blogService',
'postService'
]);
app.config(function($routeProvider) {
$routeProvider
.when('/index', {
templateUrl: 'blog_overview.html',
controller: 'IndexCtrl'})
.when('/posts', {
templateUrl: 'blog_posts.html',
controller: 'BlogPostCtrl'})
.when('/posts/:link/', {
templateUrl: 'blog_post.html',
controller: 'BlogPostCtrl'})
.otherwise({redirectTo: '/index'});
})
.run();
controllers.js:
app.controller('BlogPostCtrl', ['$scope', '$resource', '$routeParams', 'Posts',
function($scope, $resource, $routeParams, Posts){
// $scope.templateUrl = ???
Posts.getPosts(function(data){
$scope.posts = data;
})
}])
directives.js:
'use strict';
angular.module('myBlog.directives', [])
.directive('markdown', function($http){
var converter = new Showdown.converter();
return{
restrict: 'A',
scope: { link:'#' },
link: function(scope, element, attrs){
attrs.$observe('link', function(link){
$http.get('/posts/' + link).success(function(response){
var htmlText = converter.makeHtml(response);
element.html(htmlText);
});
});
}
};
});
sample from blog_post.json
[
{
"title": "first post",
"slug": "2014-06-25-first-post",
"file": "app/js/posts/2014-06-25-first-post.md",
"tags": [
{"title" : "career"}
]
}]
blog_posts.html partial:
<div ng-controller="BlogPostCtrl">Posts</div>
<div ng-repeat="post in posts">
<h2>{{post.title}}</h2>
<div markdown link=""></div>
</div>
blog_post.html partial:
<div ng-controller="BlogPostCtrl">Posts</div>
<div ng-repeat="post in posts">
<p>{{post.file}}</p>
<div markdown link=""></div>
</div>
It looks like you're trying to reinvent the wheel. Delegating markdown parsing to client side is counterproductive.
Jekyll tries to remove all the unnecessary work on server side to allow sites to be light and performance oriented.
I understand that your work can be a proof of concept but I really don't get why you're trying to do it this way, because I guess that serving static pages is far more efficient than generating them client side.

Categories