Doesn't display the object in view/html angular - javascript

I'm learning MEAN , i'm trying to display information from object, it has 2 arrays, it semms is working because I can see the object with console log of Javascript but it doesn't showing in html.
My code from javascript (books.js)
var myApp = angular.module('myApp');
myApp.controller('BooksController', ['$scope', '$http', '$location', '$routeParams',function($scope, $http, $location, $routeParams){
console.log("BooksController loaded");
$scope.getBooks = function(){
$http.get('/api/books')
.then(function(response){
console.log(response)
$scope.books = response;
});
}
}]);
My code from html (book.html)
<div class="panel panel-default" ng-init="getBooks()">
<div class="panel-heading">
<h3 class="panel-title">Latest Books</h3>
</div>
<div class="panel-body">
<div class="row">
<div ng-repeat="book in books">
<div class="col-md-3">
<div class="col-md-6">
{{book.title}}
<p>
{{book.description}}
</p>
</div>
<div class="col-md-6">
<img src="{{book.image_url}}" />
</div>
</div>
</div>
</div>
</div>
</div>
Image of getting data with console
Screenshot of object
Question is I can't figure out how to solve it, because it doesn't display in book.html.
Screenshot of book.html
I hope someone can help me.
Thanks for your help.

Your problem is the assignment of the response - it should be:
$scope.books = response.data;
Notice how in your console you have to expand data to see your array - because your response is an object, containing data as a key with your array.

You need to assign it the value of response.data
var myApp = angular.module('myApp');
myApp.controller('BooksController', ['$scope', '$http', '$location', '$routeParams',function($scope, $http, $location, $routeParams){
console.log("BooksController loaded");
$scope.books = '';
$scope.getBooks = function(){
$http.get('/api/books')
.then(function(response){
console.log(response)
$scope.books = response.data;
});
}
}]);

Related

How to display an array with html content without ng-repeat? AngularJS

I have this
"items" : ["<p>Item 1</p>","<span>Item 2</span>"]
I would like this
<div id="container">
<p>Item 1</p>
<span>Item 2</span>
</div>
How can I do it without using ng-repeat ?
You can use directly like this..
$scope.itemNames = {"items" : ["<p>Item 1</p>","<span>Item 2</span>"]};
<div ng-bind-html-unsafe="itemNames.items"> </div>
or else
use $sce.
.controller('ctrl', ['$scope', '$sce', function ($scope, $sce) {
$scope.itemNames = {"items" : ["<p>Item 1</p>","<span>Item 2</span>"]};
$scope.newNames= $sce.trustAsHtml($scope.itemNames.items);
}]);
<div ng-bind-html="newNames"> </div>
In AngularJS you can use the ng-bind-html directive to print html and for that you must include the $sanitize service.
Now, to pass the array as an html string to the view you can use Array.prototype.join():
angular
.module('App', ['ngSanitize'])
.controller('AppController', ['$scope', function ($scope) {
var obj = {
"items": ["<p>Item 1</p>","<span>Item 2</span>"]
};
$scope.items = obj.items.join('');
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.10/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-sanitize/1.5.10/angular-sanitize.min.js"></script>
<div ng-app="App" ng-controller="AppController">
<div id="container" ng-bind-html="items"></div>
</div>

Dynamically display comments with links inside using Angular JS

i have developed a comment system using Angular JS. Unfortunately if a user inserts a link in his comment, the link is not clickable in the displayed comment.
How can i achieve this ?
Here is my HTML code:
<section class="comment-list" ng-hide="loading" ng-repeat="comment in comments">
<article class="row">
<div class="col-md-2 col-sm-2 hidden-xs">
<figure class="thumbnail">
<img class="img-responsive" src="#{{ comment.user.avatar }}" />
</figure>
</div>
<div class="col-md-10 col-sm-10" style="padding-bottom: 10px;">
<div class="comment_panel panel-default arrow left">
<div class="panel-body">
<header class="text-left">
<div class="comment-user"><i class="fa fa-user"></i> #{{ comment.user.name }}</div>
<time class="comment-date"><i class="fa fa-clock-o"></i> #{{ comment.date }}</time>
</header>
<div class="comment-post">
<p ng-bind-html="sanitizedComment"></p>
</div>
</div>
</div>
</div>
</article>
The comment body is inside the #{{ comment.comment.content }}
Here is the angular controller:
angular.module('mainCtrl', [])
// inject the Comment service into our controller
.controller('mainController', function($scope, $http, $sce, Comment) {
// object to hold all the data for the new comment form
$scope.commentData = {};
$scope.sanitizedComment = $sce.trustAsHtml($scope.comment.comment.content);
// loading variable to show the spinning loading icon
$scope.loading = true;
// get all the comments first and bind it to the $scope.comments object
// use the function we created in our service
// GET ALL COMMENTS ==============
Comment.get()
.success(function(data) {
$scope.comments = data;
$scope.loading = false;
});
// function to handle submitting the form
// SAVE A COMMENT ================
$scope.submitComment = function() {
$scope.loading = true;
// save the comment. pass in comment data from the form
// use the function we created in our service
Comment.save($scope.commentData)
.success(function(data) {
// if successful, we'll need to refresh the comment list
Comment.get()
.success(function(getData) {
$scope.comments = getData;
$scope.loading = false;
});
})
.error(function(data) {
console.log(data);
});
};
// function to handle deleting a comment
// DELETE A COMMENT ====================================================
$scope.deleteComment = function(id) {
$scope.loading = true;
// use the function we created in our service
Comment.destroy(id)
.success(function(data) {
// if successful, we'll need to refresh the comment list
Comment.get()
.success(function(getData) {
$scope.comments = getData;
$scope.loading = false;
});
});
};
});
<div class="comment-post>
<p ng-bind-html="comment.comment.content"></p>
</div>
Should do the trick.

Filter files in folder and display them using ng-repeat (JS, Angular)

So, I've got some folder archives that contains unknown number of files, I know that:all of them got .7z extensionhalf starts with letters AB and other half - CD
So folder's content looks like:AB1234567890.7zAB2345678901.7zCD1234567890.7zCD2345678901.7z etc. That is I can do something like this:
Download
And on click it's gonna start downloading archive with name AB1234567890.7z. It's okay, but obviously I can't write links like that, it must be done with ng-repeat. So the question is - how to display 2 lists of links, where first list would be list with links which starts with AB and second - which starts with CD, respectively. Any help will be greatly appreciated :)
What about this:
angular.module('app',[]).controller('test', ['$scope', '$http', function($scope, $http){
//$http({ method: 'GET', url: '/getNames'}).then(function(names) {
// $scope.files = names;
//})
$scope.files = ['AB1234567890.7z',
'AB2345678901.7z',
'CD1234567890.7z',
'CD2345678901.7z'];
$scope.startWith = function(file, name){
return file.indexOf(name) == 0;
}
}])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='app' ng-controller='test'>
<p>First list</p>
<div ng-repeat='file in files' ng-if="startWith(file, 'AB')">
<a href='archives/{{file}}'>{{file}}</a>
</div>
<p>Second list</p>
<div ng-repeat='file in files' ng-if="startWith(file, 'CD')">
<a href='archives/{{file}}'>{{file}}</a>
</div>
</div>
I think this will help you
<div ng-controller="AppCtrl" layout="row" ng-cloak="" ng-app="MyApp">
<div layout="column" flex>
<a ng-repeat="file in archivesAB" href="archives/{{file}}" download="{{file}}">{{file}}</a>
</div>
<div layout="column" flex>
<a ng-repeat="file in archivesCD" href="archives/{{file}}" download="{{file}}">{{file}}</a>
</div>
</div>
(function () {
'use strict';
angular
.module('MyApp',['ngMaterial', 'ngMessages', 'material.svgAssetsCache'])
.controller('AppCtrl', AppCtrl);
function AppCtrl ($scope, $log) {
$scope.archivesAB = [
'AB1234567890.7z',
'AB2345678901.7z'
];
$scope.archivesCD = [
'CD1234567890.7z',
'CD2345678901.7z'
];
}
})();
And here is the working codepen

Angular not updating dom after array splice

I have a controller which has the test array and I have added 2 objects to it. When I call delete function from html ng-click, the array is not updated in dom but I can see that the array being spliced in js code. I have tried $apply(), but that does not work as it says it is already applied.
app.controller('HomeCtrl', ['$rootScope', '$scope', function($rootScope, $scope) {
var person1 = {firstName:"John", lastName:"Doe", age:46};
var person2 = {firstName:"Joe", lastName:"Horn", age:66};
$scope.test = [];
$scope.test.push(person1);
$scope.test.push(person2);
$scope.deletePost = function(value, post){
$scope.test.splice(0, 1);
}
}]);
HTML:
<div class="row" ng-controller="HomeCtrl">
<div ng-repeat="tes in test">{{tes.age}}<br></div>
</div>
<a data-toggle="modal" ng-click="deletePost(value, post)" data-target="#deleteModal" ng-show="post.user.email == user.email" style="font-size:15px;margin-left: 1rem;" class="card-link" href="javascript:void(0)">Delete</a>
You need to rearrange your dom and you also should splice based on index.
Try:
DOM :
<div class="row" ng-controller="HomeCtrl">
<div ng-repeat="tes in test track by $index">{{tes.age}}<br></div>
<a data-toggle="modal" ng-click="deletePost($index, tes)" data-target="#deleteModal" ng-show="post.user.email == user.email" style="font-size:15px;margin-left: 1rem;" class="card-link" href="javascript:void(0)">Delete</a>
</div>
Controller:
app.controller('HomeCtrl', ['$rootScope', '$scope', function($rootScope, $scope) {
$scope.test = [{firstName:"John", lastName:"Doe", age:46}, {firstName:"Joe", lastName:"Horn", age:66}];
$scope.deletePost = function(ind, post){
$scope.test.splice(ind, 1);
}
}]);
Move <a> inside element which has your controller attached.
<div class="row" ng-controller="HomeCtrl">
<div ng-repeat="tes in test">{{tes.age}}<br></div>
<a data-toggle="modal" ng-click="deletePost(post, value)" data-target="#deleteModal" ng-show="post.user.email == user.email" style="font-size:15px;margin-left: 1rem;" class="card-link" href="javascript:void(0)">Delete</a>
</div>

angular how to reload a controller

I have a categoriesPanel controller that on ng-click I want to show all the products belongings to that category inside my ng-controller productsPanel. The problem im having is that every time I click on the ng-click="selectorCategory" I get the all the products in the clicked category after I refresh the page.
<div class="col-md-6 m-t-10" ng-controller="productsPanel" style="padding-right:1px;">
<div class="panel panel-default" style="height: 700px">
<div class="panel-body">
<div ng-repeat="product in Products" class="productRow">
{{product.Product}}
</div>
</div>
</div>
</div>
<div class="col-md-3 m-t-10" ng-controller="categoriesPanel" style="padding-left: 0; padding-right: 5px">
<div class="panel panel-default" style="height: 700px">
<div class="panel-body">
<div ng-repeat="category in Categories" class="categoryRow">
{{category.Category}}
</div>
</div>
</div>
</div>
this is my angular script that is getting the right data from the backend but the data only shows in the producsPanel controller when i refresh the page. I want to data to show as soon as you do the ng-click.
app.controller('categoriesPanel', function($scope, $location, $http, $localStorage){
var CompanyId = $localStorage.Employee[0].CompanyId;
$http({
method : 'GET',
url : 'http://localhost:8888/categories/ajax_getCompaniesCategories',
params: {CompanyId: CompanyId}
})
.success(function(data){
$scope.Categories = data;
$localStorage.Categories = data;
});
$scope.selectedCategory = function(event){
$localStorage.CategoryId = $(event.target).data('id');
$http({
method : 'GET',
url : 'http://localhost:8888/products/ajax_getCategoryProducts',
params: {CategoryId: $localStorage.CategoryId}
})
.success(function(data){
$scope.Products = data;
$localStorage.Products = data;
});
}
});
app.controller('productsPanel', function($scope, $location, $http, $localStorage){
$scope.Products = $localStorage.Products;
});
/* END CONTROLLERS */
Maybe the product array you are pointing to gets clear when call to getcategoryproducts is made. Can you fix your callback for ajax_getCategoryProducts and change success to push elements into the array instead of reassignment.
.success(function(data){
$scope.Products.length=0;
data.forEach(function(p) {
$scope.Products.push(p);
});
$localStorage.Products = $scope.Products;
});

Categories

Resources