Angular not updating dom after array splice - javascript

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>

Related

Doesn't display the object in view/html angular

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;
});
}
}]);

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>

How to populate data in browser window?

I have a data (list of files) in $scope.data from searchFactory , Now i want to display files in browser window. How can i achieve this task ?
ctrl.js
$scope.serverFiles = function (){
$window.open($scope.data = angular.copy(searchFactory.getDitLogs()));
console.log("got function working",$scope.data);
};
main.html
<button
type="button"
class="btn btn-info btn-lg"
ng-click="serverFiles()"
style="margin-left: 10px">
<span class="glyphicon glyphicon-folder-close"></span>
</button>
declare $scope.data = [] ; then bind it to your view , so any changes it will reflect the changes . that is like this below
angular.module("app", [])
.controller('main', function($scope){
$scope.data = [];
$scope.serverFiles = function(){
//dummy record
for(i=0;i<10; i++)
$scope.data.push({sn:(i+1),name:'name of file'+i, file:'file info'+i});
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="main">
<ul>
<li ng-repeat = "info in data"><strong>{{info.sn}}</strong> {{info.name}} </li>
</ul>
<button ng-click="serverFiles()">Fetch Record</button>
</div>
</div>
anytime you manipulate the $scope.data the view would be updated

ng-repeat throwing invalid Expression

I'm a total angular noob and trying to create a simple test app where. I'd like to read out some userdata in a partial. The user data is in my event controller. I assign the event controller to a form in my new.html partial after navigating to #/new via a route controller.
The error I get when trying to loop through the users in my partial is "Error: ngRepeat:iexp Invalid Expression". I can't figure out how to ng-repeat through those users.
Any thoughts?
My index.html:
<div class="container" style="width: 500px; margin: 0 auto;">
<ul class="nav nav-pills" ng-controller="NavigationController as navigationCtrl">
<li ng-class="{active: navigationCtrl.isActive(1)}">
Home
</li>
<li ng-class="{active: navigationCtrl.isActive(2)}">
Nieuw
</li>
<li ng-class="{active: navigationCtrl.isActive(3)}">
Nog een
</li>
</ul>
<div ng-view></div>
</div>
My new.html partial
<form action="" ng-controller="EventController as event">
<div ng-repeat="users as user">
<label>Name</label>
<input type="text" class="form-control" name="name" ng-model="user.name">
<br>
<label>Emailaddress</label>
<input type="email" class="form-control" name="email" ng-model="user.email">
<br>
<input class="btn btn-default" type="submit" ng-click="event.addEvent($event)" value="Klik">
</div>
</form>
And last: My angular code
(function () {
var app = angular.module('testApp', ['ngRoute']);
app.controller('NavigationController', ['$scope', '$route', function ($scope, $route) {
$scope.$route = $route;
this.activeTab = 1;
this.setActiveTab = function (tab) {
this.activeTab = tab;
};
this.isActive = function (tab) {
if ($route.current && $route.current.activeTab) {
return $route.current.activeTab === tab;
}
return false;
};
}]);
app.controller('EventController', ['$scope', '$controller', function ($scope, $controller) {
this.users = [
{name: 'aa'},
{name: 'bb'}
];
this.addEvent = function (e) {
e.preventDefault();
console.log(this);
};
}]);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/new', {
templateUrl: 'partials/new.html',
controller: 'NavigationController',
activeTab: 2
}).
when('/another', {
templateUrl: 'partials/another.html',
controller: 'NavigationController',
activeTab: 3
}).
otherwise({
redirectTo: '/',
controller: 'NavigationController',
activeTab: 1
});
}]);
})();
I've tried changing this for $scope to no avail.
You write ng-repeat in wrong way in your new.html partial page
it should be like
new.html
<div ng-repeat="user in users">
Correct syntax for ng-repeat is
<element ng-repeat="item in [1,2,3]">
Also you can use things like track by $index if you have duplicated values in your collection like [1,1,1].
Ref. https://docs.angularjs.org/api/ng/directive/ngRepeat
There are few issues in your code. Please change all this references to $scope and then quickly fix below html code:
<div ng-repeat="user in users">
It should work but update me otherwise also.
Working demo for your reference (route codes excluded for demo purpose only)
thanks,
Ashok
you have not written ng-repeat in right way change it to:
<div ng-repeat="user in users">

AngularJS ngRepeat syntax error

Using AngularJS v1.3.15
I am getting a weird syntax error:
http://errors.angularjs.org/1.3.15/ngRepeat/iexp?p0=item%20asNaNtems
This is my template (templateUrl):
<div class="context-menu" ng-if="showMenu">
<div class="context-menu-item" ng-repeat="item as items" ng-class="{disabled: item.isDisabled()}">
<a href="" ng-click="fire(item)">
<i class="fa" ng-class="item.getIcon()"></i> {{item.getName()}}
</a>
</div>
</div>
The directive starts with a $scope.items = [] in the controller function of that directive:
angular.module('app').directive('atContextMenu', [
function() {
return {
'templateUrl': '...',
'controller': function($scope, $element) {
$scope.items = [];
}
};
}
]);
As the link says (if you have clicked on the link) you got the syntax wrong. It should be item in collection:
ng-repeat="item in items"

Categories

Resources