updating value in $scope in a sub state not working angularjs - 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.

Related

Get data from directive and change image according to data value

I want to get the value of current.flag from my template property in random.js file and use it after in my HTML file. According to the value of flag I will receive, I would like an image to be changed. I would like some help for that, because I'm beginner to Angular.
Thanks in advance
<section class="has-header">
<div class="container">
<div class="row">
<div class="col-md-4 text-center">
<img ng-src="{{current.flag === 'gr' ? 'images/image_1.png' : 'images/image_2.png'}}" />
</div>
</div>
</div>
</section>
random.js
angular.module('app')
.directive('language', function () {
return {
restrict: 'E',
replace: true,
scope: {},
template: '<div class="languages-wrap pull-right">\
<div class="languages f32">\
<div ng-click="poped=!poped" class="current flag {{current.flag}}"></div></div>\
<div class="language-selector" ng-show="poped">\
<ul class="languages-list">\
<li ng-repeat="l in langs">\
<a ng-click="changeLang(l)" class="languages f32">\
<div class="flag {{l.flag}}"></div>\
</a>\
</li>\
</ul>\
</div>\
</div>',
controller: ['$scope', '$cookies', '$translate', '$route', '$location',
function ($scope, $cookies, $translate, $route, $location) {
$scope.poped = false;
$scope.langs = [
{
iso: 'el',
flag: 'gr'
},
{
iso: 'en',
flag: 'us'
}
];
$scope.current = $cookies.getObject('lang') ? $cookies.getObject('lang') : $scope.langs[0];
$scope.changeLang = function (lang) {
$cookies.putObject('lang', lang, {expires: new Date(2020, 10, 10)});
$translate.use(lang.iso);
$scope.current = lang;
$scope.poped = false;
$location.search('lang', lang.iso);
$route.reload();
};
}
]
};
});
u can do a controller to the html file and add
$scope.current = $cookies.getObject('lang') ? $cookies.getObject('lang') : $scope.langs[0];
to the controller
if i understand correctly , u want to use the $scope.current value from a directive in another html file, which is not connected to the directive , if yes , what u can do is add a controller to this html and add the
$scope.current = $cookies.getObject('lang') ? $cookies.getObject('lang') : $scope.langs[0];
to it How to bind an AngularJS controller to dynamically added HTML?
make controller file
add it to index.html,
add this inside it
var app = angular.module('myApp', []);
app.controller('exampleCtrl', function($scope, $cookies) {
$scope.current = $cookies.getObject('lang') ? $cookies.getObject('lang') : $scope.langs[0];
});
in the html add controller to the section tag
<section class="has-header" ng-controller="exampleCtrl">

Invoke parent controller while loading child controller

I have the parent view defined as:
<div ng-app="myProSupMod" ng-controller="DefaultController" class="container">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<img src="~/Content/Images/logo.jpg" />
<b class="projectTitle">Production Support Tool</b>
</div>
</div>
<div ng-show="DefaultProps.UserDivVisible" class="page-header"
style="font-weight:bold;height:30px;border-bottom:1px solid #d1d1d4;width:100%">
<div style="float:right;"><span style="margin-right:10px;">
Welcome
<a class="text-success" href="#">
{{DefaultProps.LoggedInUsername }}
</a></span>|
<a href="#" style="margin-left:5px;" class="text-danger"
ng-click="LogUserOut()">Logout
</a>
</div>
</div>
</div>
<ng-view></ng-view>
</div>
Its controller:
myProSupMod.controller("DefaultController", ['$scope', '$rootScope',
'$location', '$route', function ($scope, $rootScope, $location, $route) {
if (!sessionStorage.getItem("LoggedInUsername")) {
$scope.DefaultProps = {
LoggedInUsername: "",
UserDivVisible: false
};
$location.path('/');
}
else {
$scope.DefaultProps = {
LoggedInUsername: sessionStorage.getItem("LoggedInUsername"),
UserDivVisible: true
};
}
$scope.LogUserOut = function () {
sessionStorage.setItem("UserDivVisible", false)
$location.path('/')
}
}])
And one of my child child controller is like
myProSupMod.controller("LoginController", ['$scope', '$rootScope',
'$uibModal', 'LoginService', '$location', function ($scope, $rootScope,
$uibModal, LoginService, $location) {
$scope.DefaultProps.LoggedInUsername = ""
$scope.DefaultProps.UserDivVisible = false
$scope.Login = {
Username: '',
Password: '',
Error: '',
validateLogin: function () {
$scope.Login.Error = ''
$scope.DefaultProps.LoggedInUsername =
sessionStorage.getItem("LoggedInUsername")
$scope.DefaultProps.UserDivVisible =
sessionStorage.getItem("UserDivVisible")
$scope.Login.Username = $scope.Login.Password = ''
$location.path('/Home')
}
}
}])
The statements
$scope.DefaultProps.LoggedInUsername=sessionStorage.getItem("LoggedInUsername")
and
$scope.DefaultProps.UserDivVisible =sessionStorage.getItem("UserDivVisible")
are really changing the values of the properties in the "Default" controller but routing to an other view both the "Default" controller properties "LoggedInUsername" and "UserDivVisible" are gone.It looks like i may need to have both the above statements in every other view i'm going to navigate to.
Is there an other way?
"Default" view being the parent, the controller is invoked only once at the start of the application upon navigating to other view the "Default" controller is never invoked.
But if i reload any page by clicking "reload" on the browser or hitting "enter" on the URL i see the "Default" controller being invoked, which is what i want to happen when i'm also navigating to other view via angular routing.
For clarity, here is a simplified template:
<div ng-app="myProSupMod" ng-controller="DefaultController">
<div ng-show="DefaultProps.LoggedInUsername">
Welcome {{DefaultProps.LoggedInUsername}}
<button ng-click="LogUserOut()">Logout<button>
</div>
<ng-view></ng-view>
</div>
Make the controller lightweight:
app.controller("DefaultController", function($scope, LoginService) {
$scope.DefaultProps = LoginService.getProps();
$scope.LogUserOut = function () {
LoginService.logout();
};
})
With the functions inside a service, they can be called by any controller and they are encapsulated in a way that makes the code easier to understand, debug, and maintain.

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

AngularJS $scope.$parent strange hierarchy

I'm trying to access the $parent in my child controller but for some reason I have to access the Fifth $parent in order to get the actual $scope from the Parent controller, Any Ideas?
Parent Controller
angular.module('App')
.controller('HomeController', ['$scope', '$rootScope', 'user',
function($scope, $rootScope, user) {
$rootScope.currentNav = 'home';
$rootScope.currentUser = user.data;
$scope.tabs = [
{
heading : 'Empresas',
template : 'home_companies_tab.html'
},
{
heading : 'Tickets',
template : 'home_tickets_tab.html'
}
];
$scope.companies = []
$scope.selectedCompanyIndex = undefined;
$scope.selectedCompany = undefined;
$scope.selectedTicketIndex = undefined;
$scope.selectedTicket = undefined;
}]);
Child Controller
angular.module('App')
.controller('HomeCompaniesTabController', ['$scope', 'Companies',
function($scope, Companies) {
$scope.loadCompanies = function () {
$scope.companies = Companies.query();
}
/**
* Init
*/
$scope.selectCompany = function (company, index) {
$scope.$parent.selectedCompanyIndex = index; //this doesnt work
$scope.$parent.$parent.$parent.$parent.$parent.selectedCompany = company; //this does, why?
console.log($scope);
}
if($scope.currentUser.security < 3) {
$scope.loadCompanies();
}
}]);
Home template
<div ng-include="'dist/templates/header.html'"></div>
<div class="container-fluid">
<div class="row">
<div class="col-xs-12">
company : {{selectedCompany}}
</div>
</div>
<tabset>
<tab ng-repeat="tab in tabs" heading="{{tab.heading}}">
<div ng-include="'dist/templates/' + tab.template" ></div>
</tab>
</tabset>
</div>
Child template
<div class="row-fluid" ng-controller="HomeCompaniesTabController">
<div class="col-md-3">
<h4>Lista de Empresas</h4>
<hr/>
<div class="list-group">
<a
href=""
class="list-group-item"
ng-repeat="company in companies"
ng-click="selectCompany(company, $index)">
<h4 class="list-group-item-heading">
{{company.name}}
</h4>
</a>
</div>
</div>
<div class="col-xs-9">
<div ng-show="selectedCompany">
<h4><b>{{selectedCompany.name}}</b></h4>
</div>
</div>
Based on the comments of charlietfl I came up with this simple service for sharing data
angular.module('App')
.factory('SharedData', [function () {
return {
}
}]);
Then I simply inject it in the controllers
angular.module('App')
.controller('HomeController', ['$scope', '$rootScope', 'user', 'SharedData',
function($scope, $rootScope, user, SharedData) {
$rootScope.currentNav = 'home';
$rootScope.currentUser = user.data;
$scope.sharedData = SharedData;
$scope.tabs = [
{
heading : 'Empresas',
template : 'home_companies_tab.html'
},
{
heading : 'Tickets',
template : 'home_tickets_tab.html'
}
];
$scope.companies = [];
}]);

AngularJS How to get data to controller via $rootScope?

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

Resources