Angularjs JSON content inside ng-view - angularjs

I am stuck in calling json text inside the ng-view. In normal HTML {{profile.experience}} this works perfect fine. fetching the data from json.
But since I have add the ng-view {{profile.experience}} is unable to fetch the data from json.
<div class="profile-snapshot">
<ul>
<li><span>Experience:</span><p> {{profile.experience}}</p></li>
<li><span>Education:</span><p> {{profile.education}}</p></li>
<li><span>Designation:</span><p>{{profile.designation}}</p></li>
<li><span>Age:</span><p>32</p></li>
<li><span>City:</span><p>Thane</p></li>
</ul>
</div>
This what my json look like
{
"experience": "Experience 8 Years asda s",
"education": "MBA, B.COM",
"designation": "UX Designer, Front End Developer"
}
this is what my angularjs code looks like
var accord = angular.module('accord', []);
var profileLoad = angular.module('profileLoad',[]);
var app2 = angular.module('main-app', ['accord','profileLoad','ngRoute']);
profileLoad.controller('profileCntrl', function($scope, $http){
'use strict';
$http.get('candidateProfile.json').success(function(data) {
$scope.profile = data;
});
});
app2.config(function($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'profile.html',
controller: 'StudentController'
})
.when('/viewStudents', {
templateUrl: 'profile-edit.html',
controller: 'StudentController'
})
.otherwise({
redirectTo: '/home'
});
});
can anyone please help me in fetching the json data inside ng-view?

Unless I'm missing something, I think
profileLoad.controller('profileCntrl', function($scope, $http){ ... }
should be
profileLoad.controller('StudentController', function($scope, $http){ ... }
You're retrieving the data in a controller that's not mapped to a template in $routeProvider.
Also, you should put your $http.get in a service and inject that service into your controller. Keep your concerns separated and your controllers lean.

Since I was already applying the controller. Only thing I needed to do is remove the controller: 'StudentController'.
That solved the problem for me.
I really appreciate the quick reply from the members here.
Cheers guys

Related

Why am I able to assign a variable to $rootScope in an Angular controller and access it in the template, but not if I assign the variable to $scope?

I am using the Angular UI Router as my router. I have a $state defined as such:
$stateProvider.state('mypage', {
url:'/',
views: {
'content': {
templateUrl: 'folder/mypage.template.html',
controller: 'MyPageController'
}
}
})
I can go to MyPageController and do the following:
$rootScope.test = "hello!";
And then go to folder/mypage.template.html and put the following:
<div id="example">
{{test}}
</div>
hello! will show up in the rendered web page. However, if I instead do the following in MyPageController:
$scope.test = "hello!";
Nothing will show up in the template. This is very confusing to me, as I know that MyPageController is made available to the state (as I can add something to $rootScope and display it), but the $scope is not available. Does anyone have an idea as to what might be going on? Thank you :)
EDIT1:
MyPageController is part of a module, let's say myModule, that is imported into a top-level module. For example, it looks something like this:
angular.module('topLevelModule', [
'myModule'
]).config( ... $stateProvider stuff ... ).run( ... setup stuff ... )
angular.module('myModule')
.controller('MyPageController', ['$scope', '$rootScope', function($scope, $rootScope) {
$scope.test = "hello!";
}]);
EDIT2 (problem solved):
I had followed a tutorial that used the following pattern with multiple states in the UI-Router:
$stateProvider
.state('mainpage', {
url: '/',
views: {
'content': {
templateUrl: 'folder/mainpage.template.html',
controller: 'MainPageController' <-- POINT OF INTEREST 1
}
}
})
.state('mypage', {
url: 'my-page',
controller: 'MyPageController', <-- POINT OF INTEREST 2
views: {
'content#': {
templateUrl: 'folder/mypage.template.html',
<-- POINT OF INTEREST 3
}
}
})
}])
However, the problem lies in this formatting. This is just a heads up for anyone using the UI-Router who happened to follow the same tutorial as I did (I can't find the link), that POINT OF INTEREST 2 needs to be moved to POINT OF INTEREST 3 for the controller to properly be assigned upon state change -- syntax error. There were more complexities to why things were happening (due to my debugging approach) that were causing any inconsistencies you see above, but I won't include them here. Thanks everyone for their time. :)
var test = angular.module('test', []);
test.run(function() {
});
test.config(function() {
// your state for binding html with controller
});
test.controller('MyPageController ', function($scope) {
$scope.test = "hello!";
});
And then in HTML
<div id="example">
{{test}}
</div>

Override AngularJS route to display template based on $scope variable

Using Angular I have a dozen or so routes setup similar to the following example code.
Is there a way to override which template and controller is loaded based on some other criteria while keeping the URL in tact? My goal is to display a login page when... lets say $scope.isLoggedIn = false. I don't want to change the URL to /login.
SomeApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/place', {
templateUrl: 'routes/place.html',
controller: 'PlaceCtrl'
})
.when('/test', {
templateUrl: 'routes/test.html',
controller: 'TestCtrl'
});
}]);
ngRoute is a very simple library that can basically only maps urls to controller/views. If you want more flexibility, try ui-router which has the ability to route based on state.
This isn't really doable with ngRoute, but with ui-router you can dynamically provide different templates based on just about anything you want.
$stateProvider.state('root',
url: '/'
controller: 'HomePageController'
templateProvider: [
'$rootScope'
'$templateCache'
'$http'
($rootScope, $templateCache, $http) ->
templateId = if $rootScope.isLoggedIn then "home-page-logged-in" else "home-page-not-logged-in"
templateId = "/templates/#{templateId}.html"
return $http.get(templateId, cache: $templateCache)
]
)
The catch is, as far as I know, you can't change the controller, only the template. Which kinda stinks.

angularJs with only one template for all category?

sorry for my English is not good !
I have followed this example phoneCat app
this is one category ( phone list and detail patial templates).
for example , i have many category, all in one category.html file (car, phone,fashion) throught url ( localhost/myApp/#/car .. localhost/myApp/#/phone..)
mainLayout
<div ng-view></div>
js file
.config(['$routeProvider',
function($routeProvider) {
$routeProvider
// route for fashion
.when('/fashion', {
templateUrl: 'partials/category.html',
controller: 'fashionCtrl'
})
// route for car
.when('/car', {
templateUrl: 'partials/category.html',
controller: 'carCtrl'
})
.. controller for fashionCtrl and carCtrl
partial template html (category.html)
template for car
...................
template for fashion
...................
template for phone
when i called the path /#/fashion it display both , but i want only one fashion or car
_So where is the solutions?
thanks for help !
It sounds like what you are looking for is to share both controller and template (common scenario)...
So instead of configuring multiple routes, you just need a single route:
.config(['$routeProvider',
function($routeProvider) {
$routeProvider
// route for fashion
.when('/:category', {
templateUrl: 'partials/category.html',
controller: 'categoryController'
})
In your controller then use $routeParams to get the currently selected category and populate your template with that common data.
.controller('categoryController', ['$scope', '$routeProvider', function($scope, $routeParams) {
$scope.category = $routeParams.category;
$scope.items = fetchFromService($routeParams.category);
}])
Sample: http://plnkr.co/edit/dtrZMAcbsbzpWsd9e7Uy?p=preview

Invoke function between two controllers while using routeprovider

I am using route provider as follows,
var appModule = angular.module('ngLogin', ['ngRoute','restangular','btford.socket-io','ngSanitize','xeditable']);
appModule.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/home', {
templateUrl: 'sample/homepage.html',
controller: 'ngHomeControl'
}).
when('/contacts', {
templateUrl: 'sample/homepage.html',
controller: 'ngContactControl'
});
}]);
Here I need to call function from ngHomeControl to ngContactControl.
I tried as follows, but the function didn't invoked.
appModule.controller('ngHomeControl', function($scope,$routeParams,socket,Restangular,$http) {
$rootScope.$broadcast('getFriendList',{"userName":userName});
});
appModule.controller('ngContactControl', function($scope,$routeParams,$rootScope,socket,sharedProperties,Restangular,$http,$timeout) {
$scope.$on("getFriendList",function(event,data)
{
console.log('getFriendList');
});
});
Can anyone help me to resolve?
This will not work as only one controller is instantiated at a time (in your case).
A proper way would be to use a service. There is a nice article that wil help you with this.
See also this answer on how to create a service.
Based on those two resources you should came up with something similar to this:
var appModule = angular.module('appModule', ['ngRoute']);
appModule.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/home', {
templateUrl: 'home.html',
controller: 'ngHomeControl'
}).
when('/contacts', {
templateUrl: 'contacts.html',
controller: 'ngContactControl'
});
}]);
appModule.service('friendsService', function(){
this.getFriendList = function () {
return ['John', 'James', 'Jake'];
}
});
appModule.controller('ngHomeControl', function($scope, friendsService) {
$scope.homeFriends = friendsService.getFriendList();
});
appModule.controller('ngContactControl', function($scope, friendsService) {
$scope.contactFriends = friendsService.getFriendList();
});
There is a complete working JSFiddle so you can test it out.
Please also checkout the console output to see when used components are instantiated.
You will see that controllers are instantiated each time the route changes - they are instantiated implicitly via the ngController directive used inside templates. The service is instantiated only once and this is at the time when it is needed/injected for the first time.
The reason your event listener isn't fired is because there isn't a ngContactControl instance alive when your at /home. You can create a parent controller, which handles the scope events but a better way is to use a service that is shared among the controllers that need this functionality.
See this plunker for an example how to share data and/or functions via a service.

AngularJS controllers causing errors

I have a very simple application that does nothing really other than display two different views depending on user selection. This application is a stepping stone to learning how routes work in AngularJS.
My issue is this.
The application when run in the browser navigates to the index view with no issues. This is because the index view does not reference a controller. However the user view does reference (require) a controller. This causes an issue where the exception thrown is Arguement 'XCtrl' is not a function, got undefined.
My main index is:
<html>
<head><title></title></head>
<body>
<div ng-view></div>
</body>
</html>
My main app.js is:
angular.module('app.controllers', []);
var controllers = angular.module('app.controllers', []);
angular.module('app', ['app.controllers'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'views/index.html'
})
$routeProvider.when('/users', {
templateUrl: 'views/users.html',
controller: 'UserCtrl'
}).
otherwise({ redirectTo: '/' });
}]);
My controller is:
appControllers.controller('UserCtrl', ['$scope', function ($scope) {
$scope.users = {
user: {name: "Ian", age: 30 },
user: {name: "Paul", age: 37 }
};
}]);
user.html
<div ng-repeat="user in users">{{user.name}} {{ user.age }}</div>
index.html
<h1>index</h1>
can anybody see where I am going wrong. Any help would be great
EDIT:
Here s the stack trace from the browser, if this helps any
Error: Argument 'UserCtrl' is not a function, got undefined
at Error ()
at bb (http://www.testapp.com/js/angular/angular.min.js:17:68)
at ra (http://www.testapp.com/js/angular/angular.min.js:17:176)
at http://www.testapp.com/js/angular/angular.min.js:53:60
at k (http://www.testapp.com/js/angular/angular.min.js:151:401)
at Object.e.$broadcast (http://www.testapp.com/js/angular/angular.min.js:90:517)
at http://www.testapp.com/js/angular/angular.min.js:83:6
at h (http://www.testapp.com/js/angular/angular.min.js:78:207)
at h (http://www.testapp.com/js/angular/angular.min.js:78:207)
at http://www.testapp.com/js/angular/angular.min.js:78:440
Also:
www.testapp.com is a locally hosted server with no external access, just in case someone tries it and can not access.
After see a related question I noticed that I had not added the UserCtrl.js to my main index.html. After adding this it worked. However, I believe there is a way to add controllers, directives, services and filters dynamically. If someone knows how to do this it would be very helpful.
Delete the brackets during assignments
angular.module('app.controllers', []);
var controllers = angular.module('app.controllers');
Or simpler do just htis:
var controllers = angular.module('app.controllers', []);
If you put the brackets you'll have two modules ...

Resources