AngularJS How to get data to controller via $rootScope? - angularjs

I'm working on an mobile app and I'm having problems with getting data to the controller. What i do is i get the data from a service and that works well (on routing this is '/' or root directory):
var listdnModule = angular.module('listdn', []);
listdnModule.factory('getActiveDnService', ['$http', function ($http) {
return {
getActiveDnSvc: function (izvajalecID) {
return $http({ method: 'POST', url: 'svc.aspx/getActiveDN', data: "{'izvajalecID':" + "'" + izvajalecID + "'}", cache: true });
}
};
}]);
listdnModule.controller('listdnCtrl', ['$scope', '$http', 'getActiveDnService','$rootScope', function ($scope, $http, svc, $rootScope) {
$scope.mjav = 1;
svc.getActiveDnSvc($scope.mjav).success(function (data) {
$rootScope.dnlist = data.d;
$scope.listdn = data.d;
});
}]);
So this works fine. It sets the data to the rootScope and to localscope and reads it from local scope.
Then i'm linking the list of Costumers to costumerdetail. The route settings are like this:
mSvc.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'tmpl/listdn.html',
controller: 'listdnCtrl'
}).
when('/settings', {
templateUrl: 'tmpl/nastavitve.html',
controller: 'settings'
}).
when('/dndetail/:dnid', {
templateUrl: 'tmpl/dndetail.html',
controller: 'dndetailCtrl'
}).
otherwise({
redirectTo: '/'
});
}]);
The error comes after i try to get dndetail. I get the right ID from $routeParams but i dont get the data in the right time. The code is this:
var dndetail = angular.module('dndetail', []);
dndetail.controller('dndetailCtrl', ['$rootScope', '$scope', '$routeParams', function ($rootScope, $scope, $routeParams) {
console.log($rootScope.dnlist[0]);
$scope.datal = $rootScope.dnlist;
$scope.id = $routeParams.dnid;
for(var i = 0; i <= datal.length; i++) {
if (datal[i].ID === $scope.id) {
$scope.data = datal[i];
}
}
}]);
And this is the error i get:
As you can see the console.log gets the object and prints the output (I masked it because it's company data) while datal is undefined. The special AngularJS tab in chrome DevTools also says the data is there:
And for the end the template of the view that doesnt get data:
<ul ng-controller="dndetailCtrl" class="list-group">
<li class="list-group-item">
<div class="row info-row-li">
<div class="pull-left">Naslov</div>
<div class="pull-right">
<a ng-href="https://maps.google.com/?q={{ data.Ulica }} {{ data.Posta }} {{ data.Kraj }}">
{{ $root.dnlist[1].Ulica }}<br />
{{ data.Posta }} {{ data.Kraj }}<br />
{{ data.Drzava }}</a>
</div>
</div>
</li>
<li class="list-group-item">
<div class="row info-row-li">
<div class="pull-left">Datum izvedbe</div>
<div id="kupec-pe" class="pull-right">{{ data.DatumIzvedbe }}</div>
</div>
</li>
<li class="list-group-item">
<div class="row info-row-li">
<div class="pull-left">Datum naloga</div>
<div id="kupec-dst" class="pull-right">{{ data.DatumNaloga }}</div>
</div>
</li>
<li class="list-group-item">
<div class="row info-row-li">
<div class="pull-left">Opis:</div>
<div id="kupec-komerc" class="pull-right">{{ data.Opis }}</div>
</div>
</li>
<li class="list-group-item">
<div class="row info-row-li">
<div class="pull-left">Šifra dejavnosti:</div>
<div id="kupec-sif" class="pull-right">{{ data.sifDej }}</div>
</div>
</li>
<li class="list-group-item">
<div class="row info-row-li">
<div class="pull-left">Šifra dejavnosti:</div>
<div id="Div1" class="pull-right">{{ data.DatumIzvedbe }}</div>
</div>
</li>
</ul>
Any ideas?
UPDATE
This is the new controller:
dndetail.controller('dndetailCtrl', ['$rootScope', '$scope', '$routeParams', function ($rootScope, $scope, $routeParams) {
$rootScope.dnlist;
$scope.id = $routeParams.dnid;
for (var i = 0; i <= $rootScope.dnlist.length; i++) {
if ($rootScope.dnlist[i].ID === $scope.id) {
$scope.data = $rootScope.dnlist[i];
}
}
}]);
still doesnt work. From an array of elements i want to get one element by id and then save it to data so i can read from data. For loop doesnt get the data (unindentified dnlist) but if i bind {{ $root.dnlist[1].Property }} in the template it works.

I don't think problem is fixed by this answer and tried to delete it, I have undelete it as it has been referred in a comment.
$http in angularjs returns a promise, you can't use the promise directly to access the data, check this answer where it answer something very similar.

If anyone was wondering the problem was with the equality operator. If I change === with the one that checks type == i dont get the TypeError: Cannot read property 'ID' of undefined error any more. Since this is the solution to the problem I'd like to have an explanation also. I'm a javascript beginner to be true and if someone got an idea what happened here, I'd very much like to know the explanation.
The new controller that works:
dndetail.controller('dndetailCtrl', ['$rootScope', '$scope', '$routeParams', function ($rootScope, $scope, $routeParams) {
$rootScope.dnlist;
$scope.id = $routeParams.dnid;
for (var i = 0; i <= $rootScope.dnlist.length; i++) {
if ($rootScope.dnlist[i].ID == $scope.id) {
$scope.data = $rootScope.dnlist[i];
}
}
}]);

Related

TypeError: Cannot read property 'childNodes' of undefined at f (angular.min.js:62)at angular.min.js:62 "<div ng-view="" class="ng-scope">"

I have been facing this from a long time, it is thrown when I'm trying to bind data to a variable in the html using {{}}. I used ngRoute for routing among different pages. The above mentioned error occurs when I'm trying to bind data to a variable or ng-model in the HTML.
But it works fine when the model's value is already declared in the controller.
The data that I'm receiving is from a custom service, which eventually makes an http GET request upon calling it from a controller.
<html ng-app="bgpsApp">
<body>
<div ng-view></div>
</body>
<!-- scripts loaded in a sequence:
jquery, angular.js(1.6.9), angular-route.js, app.js, customservices.js -->
</html>
app.js
var bgpsapp = angular.module('bgpsApp', ['ngRoute']);
bgpsapp.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'brahmagpslogin.html'
})
.when('/portal', {
resolve: {
"check": function($location, $rootScope) {
if (!$rootScope.logStatus) {
$location.path('/');
}
}
},
templateUrl: 'portal.html'
})
.otherwise({
redirectTo: '/'
})
})
bgpsapp.controller('MainController', ['$scope', '$rootScope', '$http', 'services', function($scope, $rootScope, $http, services) {
services.getDashboardData($rootScope.master.userId).then(function(response) {
$scope.vehiclesStatus = response.data.data.vehiclesStatus;
console.log($scope.vehiclesStatus);
// ** assigning value to bind **
$scope.vehicleCount = $scope.vehiclesStatus.vehicleCount;
}, function(response) {
alert(response.data.message);
});
}]);
portal.html
<div id="wrapper" ng-controller="MainController">
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-7 col-lg-7">
<h4>Vehicles
<small> Status</small>
</h4>
</div>
<div class="col-xs-12 col-sm-12 col-md-5 col-lg-5">
<h4>
<!-- trying to bind data to this variable -->
{{vehicleCount}}
<small>Trucks</small>
</h4>
</div>
</div>
</div>
custom service js
bgpsapp.service('services', function($http) {
this.baseURL = "http://xxx/api/data";
this.getDashboardData = function(customerId) {
var d_response = {};
var response = $http.get(this.baseURL + "/customer/data/dashboard?userId=" + customerId);
return response;
}
});

it just keep loading the same page with angular ngRoute?

I am learning angular by building a simple bookstore web app using nodejs as a restful api server. I built the server and it works fine, but once it comes to the front end I face an issue. I built the main page using angular ngRoute to get the data from the server and presented as following:
the picture and the title and the description angular read it with no problem but once I press the button "View Details" I should be redirected to a details page using the book id from the server.
From the front End the route provider:
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function($routeProvider){
$routeProvider.when('/',{
controller: 'BooksController',
templateUrl: 'views/books.html'
})
.when('/books',{
controller: 'BooksController',
templateUrl: 'views/books.hrml'
})
.when('/books/details/:id',{
controller: 'BooksController',
templateUrl: 'views/book_details.html'
})
.when('/books/add', {
controller: 'BooksController',
templateUrl: 'views/add_book.html'
})
.when('/books/edit/:id', {
controller: 'BooksController',
templateUrl: 'views/edit_book.html'
})
.otherwise({
redirectTo: '/'
})
});
Books Controller:
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){
$scope.books = response.data;
});
}
$scope.getBook = function(){
var id = $routeParams.id;
$http.get('/api/books/'+id).then(function(response){
$scope.book = response.data;
});
}
}]);
books html where the panel being designed:
<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-6">
<div class="col-md-6">
<h4>{{book.title}}</h4>
<p>{{book.description}}</p>
<a class="btn btn-primary"
href="#/books/details/{{book._id}}">View Details</a>
</div>
<div class="col-md-6">
<img class="thumbnail" src="{{book.image_url}}">
</div>
</div>
</div>
</div>
</div>
</div>
This the details book html where by clicking the button it must be redirected to:
details_book.html
<div class="panel panel-default" ng-init="getBook()">
<div class="panel-heading">
<h3 class="panel-title">{{book.title}}</h3>
</div>
<div class="panel-body">
<div class "row">
<div class ="col-md-4">
<img src="{{book.image_url}}">
</div>
<div class ="col-md-8">
<p>{{book.description}}</p>
<ul class="list-group">
<li class="list-group-item">Genre: {{book.genre}}</li>
<li class="list-group-item">Author: {{book.author}}</li>
<li class="list-group-item">Publisher: {{book.publisher}}
</li>
</ul>
</div>
</div>
</div>
</div>
and this is the get request from the server to prove the server working find using a certain id
The error I get once I open the main page:
And this error I get once I press the button:
Note: Once I press the button it give me this url:
http://localhost:3000/#!/#%2Fbooks%2Fdetails%2F599701c1f3da51117535b9ab
where the id is 599701c1f3da51117535b9ab which we can see it in the end of the url. But it should give url exactly such as:
http://localhost:3000/#!/books/details/599701c1f3da51117535b9ab
and once I write this url manually I get to the page which is the details with no problem but once I press the button from the book.html page I get the previews strange url again which is:
http://localhost:3000/#!/#%2Fbooks%2Fdetails%2F599701c1f3da51117535b9ab
Which load no where.
This is the github url for all the documents:
https://github.com/AbdallahRizk/BookStore.git
Any suggestions Please!!
use $rootScope instead of $scope for getBook function
$rootScope.getBook = function(){
var id = $routeParams.id;
$http.get('/api/books/'+id).then(function(response){
$scope.book = response.data;
});
init(getBook);
}
Note: add $rootScope to your BookController
Seems like I have hashprefix !, then my URL should also have ! after hash(#)
href="#!/books/details/{{book._id}}"
Since Angular 1.6 hashprefix is defaulted to !, you can disable this behavior by setting hashPrefix to ''(blank).
.config(['$locationProvider',
function($locationProvider) {
$locationProvider.hashPrefix('');
}
]);
Note: This answer from, #Pankaj Parkar at I get a weird templateURL not as it suppose to give with angular?

How to bind and parse HTML content retrieved from database via Json

I'm using AngularJS 1.5.8.
I'm trying to bind {{card.reading}} in the view, but the data is rendered as text
html
<div ng-app="myApplication" ng-controller="postController as tarot">
<ul>
<li class="card" ng-repeat="card in tarot">
<img class="card" src="app/images/cards/{{card.value}}.png" alt="card.name">
<article>{{card.reading | unsafe}}</article>
</li>
</ul>
</div>`
JavaScript
var app = angular.module('myApplication', []);
app.controller('postController', function($scope, $http, $filter, $sce) {
$scope.$sce = $sce;
var url = './api.php/tarot';
$http.get(url).success(function(response) {
$scope.tarot = php_crud_api_transform(response).tarot;
});
});
app.filter('unsafe', function($sce){
return $sce.parseAsHtml;
});
exemple of JSON
{
"id":1,
"name": "Test",
"value": "1",
"reading": "<h2>Lorem Ipsum</h2><p>Lorem ipsum</p>"
}
Updating your HTML as such should do the trick..
<div ng-app="myApplication" ng-controller="postController as tarot">
<ul>
<li class="card" ng-repeat="card in tarot">
<img class="card" src="app/images/cards/{{card.value}}.png" alt="card.name">
<article ng-bind-html="card.reading"></article>
</li>
</ul>
</div>`
Thank you, it's solved now.
JavaScript
var app = angular.module('myApplication', ['ngSanitize'])
.controller('postController', ['$scope', '$http', '$sce',
function postController($scope, $http, $sce) {
var url = './api.php/tarot';
$http.get(url).success(function(response) {
$scope.tarot = php_crud_api_transform(response).tarot
});
$scope.explicitlyTrustedHtml = $sce.trustAsHtml();
}
]);
and the HTML as you suggested. :)
There is another solution . you can modify you code a little bit and it will work.
<div ng-app="myApplication" ng-controller="postController as tarot">
<ul>
<li class="card" ng-repeat="card in tarot">
<img class="card" src="app/images/cards/{{card.value}}.png" alt="card.name">
<article ng-bind-html="card.reading | unsafe"></article>
</li>
</ul>
</div>`
change your filter to ,
app.filter('unsafe', function($sce) {
return function(text) {
return $sce.trustAsHtml(text);
}
});
This will work.

updating value in $scope in a sub state not working angularjs

I have a parent state which shows the list of apartments, on clicking any apartment a sub state is loaded which shows all the images for it. But value of $scope is not passing to ng-repeat. What possible mistake i have made here.
app.js :
state('projects', {
url: '/projects',
templateUrl : 'resources/partials/projectsNew.html',
controller : 'ProjectsController'
}).state('projects.project', {
url: '/project/:param',
templateUrl : 'resources/partials/projectImages.html',
controller : 'ProjectController'
})
Controllers :
decorpotCtrls.controller('ProjectsController', [ '$scope', 'cart', 'projects', '$rootScope',
function($scope, cart, projects, $rootScope) {
projects.getAllProjects().success(function(data) {
for (var i = 0; i < data.length; i++) {
data[i].APARTMENT = data[i].APARTMENT.replace(/\s+/g, '-');
}
$scope.projects = data;
});
} ]);
decorpotCtrls.controller('ProjectController', [
'$scope',
'cart',
'projects',
'$stateParams',
'$rootScope',
function($scope, cart, projects, $stateParams, $rootScope) {
var project = $stateParams.param;
projects.getImagesByAppartment(project).success(function(data) {
$scope.images = data;
console.log($scope.images);
});
} ]);
html :
ProjectsNew.html :-
<div class="pastProjects" ui-view>
<div class="col-md-3 .col-xs-12 .col-sm-6 imgContainerOuter"
ng-repeat="project in projects | filter:query">
<div class="imgContainer">
<a class="shrink"ui-sref="projects.project({param : '{{project.APARTMENT}}'})">
<img src={{project.SMALL_PATH}}>
</a>
</div>
<div class="textProjects">
<h4>{{project.APARTMENT}}</h4>
<span>Bangalore</span>
</div>
</div>
projectImages.html :-
<div id="gallery">
<a href="{{image.HD_PATH}}" ng-repeat="image in images | filter:query">
<img src="{{image.SMALL_PATH}}" alt="Photo 1" /></a>
</div>
when i am navigating from parent state projects to project ng-repeat doesnt works. I put a console log in ProjectController for the value of images its being populated correctly.

routeProvider in angularJS not acting right

Within my view I am outputting links. When I go to click a link it triggers the otherwise method in my routeProvider and ends up redirecting back to home. I need it to redirect indiv id and I need to be able to grab project.id from my view within my controller. May I please have some assistance. I'm kind of stuck.
My view:
<div class="container clearfix">
<div class="pagename sixteen columns fadeInUp animated">
<h1 style="font-family: Merriweather">Portfolio</h1>
</div>
</div>
<div class="container clearfix" ng-controller="portfolioController">
<ul style="padding-left: 20pt" class="large-block-grid-4 align-center">
<li class="part" ng-repeat="project in projects">
<a href="#/indiv?id={{ project.id }}">
<img src="{{ project.screenshot_uri }}" alt="">
</a>
<br><br>
<h4>{{ project.project_name }}</h4>
<p>{{ project.description }}</p>
</li>
</ul>
</div><br><br>
My app data:
var app = angular.module("app", ['ngRoute']).config(function($httpProvider, $routeProvider) {
$routeProvider.when('/home', {
templateUrl: 'index.php/projects/projects/home',
controller: 'homeController'
});
$routeProvider.when('/portfolio', {
templateUrl: 'index.php/projects/projects/portfolio',
controller: 'portfolioController'
});
$routeProvider.when('/indiv:id', {
templateUrl: 'index.php/projects/projects/indiv',
controller: 'indiv_controller'
});
$routeProvider.when('/contact', {
templateUrl: 'index.php/projects/projects/contact',
controller: 'contactController'
});
$routeProvider.otherwise({ redirectTo: '/home' });
});
app.factory('pull_projects', function($http) {
return {
get_projects: function(callback) {
$http.get('index.php/projects/pull_projects').success(callback);
}
};
});
app.controller('portfolioController', function($http, $location, $scope, pull_projects) {
pull_projects.get_projects(function(results) {
$scope.projects = results;
});
});
app.controller('contactController', function($http, $location, $scope) {
});
app.controller('indiv_controller', function($http, $location, $scope, $routeParams) {
alert($routeParams.id);
});
app.controller('homeController', function($http, $location, $scope) {
});
Seems the problem is that you are defining the angular routing url and the url in the markup slightly different.
Route:
In the route url you are defining /indiv:id. However, this would match a url where the id was part of the indiv part. So, http://host/indiv123.
So, I would suggest changing this to: /indiv/:id. This will then match urls like this: http://host/indiv/123.
Markup:
In the HTML you are declaring the url as #/indiv?id={{ project.id }}. This will produce the url: /indiv?id=123.
To match our new angular route we need the template to be #/indiv/{{ project.id }} so that we produce a url like /indiv/123.
Hope this helps.
You should use :
ng-href="#/indiv?id={{ project.id }}"
instead of
href="#/indiv?id={{ project.id }}"
This ensures that {{ project.id }} is correctly resolved before it is used as a link.
This occurs because Angular not always gets the chance to intercept the data binding requests before the browser attempts to resolve href and src (<img src="">) attributes. Accordingly, you should use ng-src for images.

Resources