How to do preloader for `ng-view` in Angular JS? - angularjs

I use <div ng-view></div> on web page.
When I click link in block <div> is loaded HTML template was set in routeProvider. Also together is done request AJAX that returns data that was loaded template.
Now problem is that after click I get HTML template with empty form, still is working AJAX request. After some seconds form HTML is fiiled data from AJAX.
How I can do preloader to page for directory ng-view?

It seems that there are some similar questions here:
Angularjs loading screen on ajax request
Angular JS loading screen and page animation.
Also, there a bunch of modules to work with loading animation at http://ngmodules.org. For example, these:
https://github.com/cgross/angular-busy
https://github.com/chieffancypants/angular-loading-bar (I use this one in my apps)
https://github.com/McNull/angular-block-ui and other.
UPD:
I've written a simple solution based on how the angular-loading-bar works. I didn't test it with ng-view, but it seams to work with ui-view. It is not a final solution and have to be polished.
angular.module('ui')
.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('LoadingListener');
}])
.factory('LoadingListener', [ '$q', '$rootScope', function($q, $rootScope) {
var reqsActive = 0;
function onResponse() {
reqsActive--;
if (reqsActive === 0) {
$rootScope.$broadcast('loading:completed');
}
}
return {
'request': function(config) {
if (reqsActive === 0) {
$rootScope.$broadcast('loading:started');
}
reqsActive++;
return config;
},
'response': function(response) {
if (!response || !response.config) {
return response;
}
onResponse();
return response;
},
'responseError': function(rejection) {
if (!rejection || !rejection.config) {
return $q.reject(rejection);
}
onResponse();
return $q.reject(rejection);
},
isLoadingActive : function() {
return reqsActive === 0;
}
};
}])
.directive('loadingListener', [ '$rootScope', 'LoadingListener', function($rootScope, LoadingListener) {
var tpl = '<div class="loading-indicator" style="position: absolute; height: 100%; width: 100%; background-color: #fff; z-index: 1000">Loading...</div>';
return {
restrict: 'CA',
link: function linkFn(scope, elem, attr) {
var indicator = angular.element(tpl);
elem.prepend(indicator);
elem.css('position', 'relative');
if (!LoadingListener.isLoadingActive()) {
indicator.css('display', 'none');
}
$rootScope.$on('loading:started', function () {
indicator.css('display', 'block');
});
$rootScope.$on('loading:completed', function () {
indicator.css('display', 'none');
});
}
};
}]);
It can be used like this:
<section class="content ui-view" loading-listener></section>

You can try something like this(simplest solution):
Set your loader animation/picture:<div class="loader" ng-show="isLoading"></div>
On div element add click event:
Then AJAX request success set isLoading=true

Download javascript and css files from PACE Loader.
Playing around with pace loader using ng-views . Hope this helps someone trying to use PACE.JS with Angular. In this example I am using ng-router to navigate between views.
app.js
var animateApp = angular.module('route-change-loader', ['ngRoute']);
var slowResolve = function(slowDataService){
return slowDataService.getContacts();
};
slowResolve.$inject = ['slowDataService'];
// ROUTING ===============================================
// set our routing for this application
// each route will pull in a different controller
animateApp.config(function($routeProvider) {
$routeProvider
// home page
.when('/route1', {
templateUrl: 'route1.html',
controller: 'slowCtrl',
controllerAs:'ctrl',
resolve: {
contacts:slowResolve
}
})
.otherwise({
templateUrl:'default.html'
});
});
var SlowCtrl = function(contacts) {
this.contacts = contacts;
};
SlowCtrl.$inject = ['contacts'];
angular.extend(SlowCtrl.prototype, {
message:'Look Mom, No Lag!',
contacts: []
});
animateApp.controller('slowCtrl', SlowCtrl);
var SlowDataService = function($timeout){
this.$timeout = $timeout;
};
SlowDataService.$inject = ['$timeout'];
angular.extend(SlowDataService.prototype, {
contacts:[{
name:'Todd Moto',
blog:'http://toddmotto.com/',
twitter:'#toddmotto'
},{
name:'Jeremy Likness',
blog:'http://csharperimage.jeremylikness.com/',
twitter:'#jeremylikness'
},{
name:'John Papa',
blog:'http://www.johnpapa.net/',
twitter:'#John_Papa'
},{
name:'Josh Carroll',
blog:'http://www.technofattie.com/',
twitter:'#jwcarroll'
}],
getContacts:function(){
var _this = this;
return this.$timeout(function(){
return angular.copy(_this.contacts);
}, 1000);
}
});
animateApp.service('slowDataService', SlowDataService);
index.html
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Test Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<link rel="stylesheet" href="pace.css">
<script src="http://code.angularjs.org/1.2.13/angular.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular-route.js"></script>
<script src="app.js"></script>
<script src="pace.js"></script>
</head>
<body ng-app="route-change-loader">
<div class="container">
<div class="masthead">
<ul class="nav nav-tabs">
<li>
Default
</li>
<li>
Slow Loading Controller
</li>
</ul>
</div>
<!-- Jumbotron -->
<div class="row">
<route-loading-indicator></route-loading-indicator>
<div ng-if="!isRouteLoading" class="col-lg-12" ng-view=""></div>
</div>
<!-- Site footer -->
<div class="footer">
<p>by <b>Ritesh Karwa</b> </a>
</p>
</div>
</div>
</body>
</html>
default.html
<h1>Click on the tabs to change routes</h1>
route1.html
<h1>{{ctrl.message}}</h1>
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Blog</th>
<th>Twitter</th>
</tr>
</thead>
<tbody>
<tr ng-repeat='contact in ctrl.contacts'>
<td>{{contact.name}}</td>
<td>{{contact.blog}}</td>
<td>{{contact.twitter}}</td>
</tr>
</tbody>
</table>

Related

When clicking very quickly on Angularjs app page doesn't load

FYI - I am very new to Angular...not my code mostly from tutorial on Lynda which I am playing with.
I noticed when I am doing a type of "pagination" where I am showing different elements from a data.json file, the page doesn't load if I click page back anchor links too quickly to show the next or previous item. The culprit begins somewhere as a result of the anchor tags here (details.html file) / in the controller of details. I am wondering if it's async/await not being used issue.
<div class="container">
<div class="row">
<div class="col-12 mt-3">
<div class="card">
<div class="card-header d-flex align-items-start justify-content-between">
<h1 class="card-title my-0">{{artists[whichItem].name}}</h1>
<nav class="btn-group">
<a class="btn btn-sm btn-secondary"
href="#/details/{{prevItem}}"><</a>
<a class="btn btn-sm btn-secondary"
href="#/">•Home</a>
<a class="btn btn-sm btn-secondary"
href="#/details/{{nextItem}}">></a>
</nav>
</div>
<div class="card-body"
ng-model="artists">
<h4 class="card-title text-dark mt-0">{{artists[whichItem].reknown}}</h4>
<img class="float-left mr-2 rounded"
ng-src="images/{{artists[whichItem].shortname}}_tn.jpg"
alt="Photo of {{artists[whichItem].name}}">
<div class="card-text text-secondary">{{artists[whichItem].bio}}</div>
</div>
</div>
</div>
</div>
</div>
In the meantime - By searching different things online I added a
.otherwise({
redirectTo: '/'
});
a redirect so something shows up. It'd be great if someone can please help explain what's causing that and how to fix it. I am posting the code below. I also added console.logs to help me debug in my controller, but I was not successful.
My smaller controller - (controllers.js):
var myControllers = angular.module('myControllers', []);
myControllers.controller('SearchController', function MyController($scope, $http) {
$scope.sortArtistBy = 'name';
$http.get('js/data.json').then(
(response) => $scope.artists = response.data
);
});
myControllers.controller('DetailsController', function MyController($scope, $http, $routeParams) {
$http.get('js/data.json').then(
function(response) {
$scope.artists = response.data
$scope.whichItem = $routeParams.itemId;
if($routeParams.itemId > 0){
$scope.prevItem = Number($routeParams.itemId) - 1;
console.log("I am going to 18")
} else {
console.log("I am going to 20")
$scope.prevItem = $scope.artists.length - 1;
}
if($routeParams.itemId < $scope.artists.length - 1){
console.log("I am going to 25")
$scope.nextItem = Number($routeParams.itemId) + 1;
} else {
console.log("I am going to 28")
$scope.nextItem = 0;
}
}
);
});
My main app controller (app.js):
var myApp = angular.module('myApp', [
'ngRoute',
'myControllers'
]);
myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'js/partials/search.html',
controller: 'SearchController'
})
.when('/details/:itemId', {
templateUrl: 'js/partials/details.html',
controller: 'DetailsController'
})
.otherwise({
redirectTo: '/'
});
}]);
My (index.html) file:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8">
<title>AngularJS</title>
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="lib/bootstrap/bootstrap.min.css">
<link rel="stylesheet" href="css/style.css">
<script src="lib/angular/angular.min.js"></script>
<script src="lib/angular/angular-route.min.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
</head>
<body class="bg-secondary">
<div ng-view></div>
<script src="lib/jquery/jquery.min.js"></script>
<script src="lib/bootstrap/popper.min.js"></script>
<script src="lib/bootstrap/bootstrap.min.js"></script>
</body>
</html>
One approach is to cache the data in a service:
app.service("dataService", function($http) {
var cache;
this.get = () => {
cache = cache || $http.get('js/data.json');
return cache;
};
})
Then in the controller:
app.controller('DetailsController', function MyController($scope, dataService, $routeParams) {
dataService().then(
function(response) {
$scope.artists = response.data
$scope.whichItem = $routeParams.itemId;
//...
}
);
});
By caching the $http promise, the app avoids repeating identical requests to the server.

Angular loading Controllers and Services

I am using Angularjs for my application.I am having one common page which has header and footer which i am making common for all pages.Thats y i am placing it in one common html.Only contents code i am placing in other html pages.
As i am using one common page i am loading all controllers and all Services that i am using in the application.
Here is my commonpage.html
<!DOCTYPE html>
<html lang="en" data-ng-app="adminApp">
<head>
</head>
<body>
<!--Here is header code-->
<div class="LeftMenu">
<ul class="navbar">
<a href="#!/admindashboardhome" title="Dashboard"><li>
<span>Dashboard</span></li>
</a>
<a href="#!/examinationhalltickets" title="Declaration"><li>
<span>Examination Form</span></li>
</a>
<a href="#!/collegedetails" title="Declaration"><li>College
Details</li>
</a>
</ul>
</div>
<!--followed by footer code-->
<div data-ng-view> <!--ng-view-->
</div>
<!--Here i am loading all controllers and services related to application-->
<script
src="resources/angular/controller/admin/AdminExamController.js">
</script>
<script src="resources/angular/service/admin/AdminExamService.js">
</script>
<!-- And many more in same fashion-->
</body>
</html>
The doubt i am having is,is it necessary to place all controllers and services like i am doing because i am facing performance issue even though i am connected to strong internet it loads very slow.As i am placing all in one page it is loading all controllers and services everytime.If i place controllers in their respective html then i am getting error like ExamController.js or any .js Controller not defined.Is there any other way that i can load all controllers and services so that i can increase the performance of the application?
I think this is what your looking for
app.js
/* Module Creation */
var app = angular.module ('adminApp', ['ngRoute']);
app.config(['$routeProvider', '$controllerProvider', function($routeProvider, $controllerProvider){
/*Creating a more synthesized form of service of $ controllerProvider.register*/
app.registerCtrl = $controllerProvider.register;
function loadScript(path) {
var result = $.Deferred(),
script = document.createElement("script");
script.async = "async";
script.type = "text/javascript";
script.src = path;
script.onload = script.onreadystatechange = function (_, isAbort) {
if (!script.readyState || /loaded|complete/.test(script.readyState)) {
if (isAbort)
result.reject();
else
result.resolve();
}
};
script.onerror = function () { result.reject(); };
document.querySelector("head").appendChild(script);
return result.promise();
}
function loader(arrayName){
return {
load: function($q){
var deferred = $q.defer(),
map = arrayName.map(function(name) {
return loadScript(name+".js");
});
$q.all(map).then(function(r){
deferred.resolve();
});
return deferred.promise;
}
};
}
$routeProvider
.when('/view2', {
templateUrl: 'view2.html',
resolve: loader(['Controller2'])
})
.when('/bar',{
templateUrl: 'view1.html',
resolve: loader(['Controller1'])
})
.otherwise({
redirectTo: document.location.pathname
});
}]);
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.min.js"></script>
</head>
<body ng-app="adminApp">
<!--Here is header code-->
<div class="LeftMenu">
<ul class="navbar">
<a href="#!/admindashboardhome" title="Dashboard"><li>
<span>Dashboard</span></li>
</a>
<a href="#!/examinationhalltickets" title="Declaration"><li>
<span>Examination Form</span></li>
</a>
<a href="#!/collegedetails" title="Declaration"><li>College
Details</li>
</a>
</ul>
</div>
<!--followed by footer code-->
<div data-ng-view> <!--ng-view-->
</div>
<!--Here i am loading all controllers and services related to application-->
<script
src="app.js">
</script>
<!-- And many more in same fashion-->
</body>
</html>
Controller 1.js
(function(val){
'use strict';
angular.module('Controller1App', [])
.controller('Controller1', ['$http','$rootScope','$scope','$window', function($http,$rootScope, $scope, $window){
//Your code goes here
}])
})(this);
Controller 2.js
(function(val){
'use strict';
angular.module('Controller2App', [])
.controller('Controller2', ['$http','$rootScope','$scope','$window', function($http,$rootScope, $scope, $window){
//Your code goes here
}])
})(this);
Refer https://plnkr.co/edit/cgkgG5PCwJBVOhQ1KDW2?p=preview

How can you do server side paging with Angular's UI Bootstrap pagination directive

Hi we are wanting to do server side paging with Angular's UI Bootstrap pagination directive. We know how to create a RESTful endpoint to serve up the pages from our servers but didn't see any documentations about how to hook that endpoint up to Angular's UI Bootstrap pagination directive.
Please see small demo below
angular.module('app', ['ui.bootstrap']);
angular.module('app').controller('PaginationDemoCtrl', function($scope, $http) {
$scope.currentPage = 1;
$scope.limit= 10;
$scope.tracks = [];
getData();
function getData() {
$http.get("https://api.spotify.com/v1/search?query=iron+&offset="+($scope.currentPage-1)*$scope.limit+"&limit=20&type=artist")
.then(function(response) {
$scope.totalItems = response.data.artists.total
angular.copy(response.data.artists.items, $scope.tracks)
});
}
//get another portions of data on page changed
$scope.pageChanged = function() {
getData();
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.12.0.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
<body ng-app="app">
<div ng-controller="PaginationDemoCtrl">
<h4>Sample Server Pagination</h4>
<pagination total-items="totalItems" ng-model="currentPage" ng-change="pageChanged()" items-per-page="100"></pagination>
<ul>
<li ng-repeat="track in tracks" style="list-style:none">
<img ng-src="{{track.images[2].url}}" alt="" width="160"/>
{{track.name}}</li>
</ul>
</div>
</body>
angular.module('app', ['ui.bootstrap']);
angular.module('app').controller('PaginationDemoCtrl', function($scope, $http) {
$scope.currentPage = 1;
$scope.tracks = [];
getData();
function getData() {
$http.get("https://ws.spotify.com/search/1/track.json?q=kaizers+orchestra&page=" + $scope.currentPage)
.then(function(response) {
$scope.totalItems = response.data.info.num_results
angular.copy(response.data.tracks, $scope.tracks)
});
}
//get another portions of data on page changed
$scope.pageChanged = function() {
getData();
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.12.0.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
<body ng-app="app">
<div ng-controller="PaginationDemoCtrl">
<h4>Sample Server Pagination</h4>
<pagination total-items="totalItems" ng-model="currentPage" ng-change="pageChanged()" items-per-page="100"></pagination>
<ul>
<li ng-repeat="track in tracks">{{track.name}}</li>
</ul>
</div>
</body>

Angularjs modal window with routeProvider

I'm having trouble using routeProvider to display a modal window. I am displaying a table list of ingredients and hoping that by clicking on an ingredient, I can display an "update" modal. The table displays properly and I can even view a single ingredient outside of a modal context but as soon as I try and get the modal working everything falls apart - in fact, the modal doesn't even properly receive its "ingredient" variable. When clicking on a table row the HTML for the modal is displayed like it's a separate page.
app.js:
angular.module('IngredientsApp', [
'IngredientsApp.controllers',
'IngredientsApp.services',
'ngRoute',
'ui.bootstrap'
]).config(['$routeProvider', function($routeProvider) {
$routeProvider.
when("/ingredients", {templateUrl: "partials/ingredients.html", controller: "ingredientsController"}).
when("/ingredient/:id", {templateUrl: "partials/ingredient.html", controller: "ingredientController"}).
otherwise({redirectTo: '/ingredients'});
}]);
services.js:
angular.module('IngredientsApp.services', []).factory('ingredientAPIservice', function($http) {
var ingredientAPI = {};
ingredientAPI.getIngredients = function() {
return $http.get('/ingredient');
}
ingredientAPI.getIngredient = function(id) {
return $http.get('/ingredient/'+id+'/edit');
}
return ingredientAPI;
});
index.html
<!doctype html>
<html lang="en">
<head>
<title>Our Recipes</title>
<script type="text/javascript" src="/js/angular.min.js"></script>
<script type="text/javascript" src="/js/angular-route.min.js"></script>
<script type="text/javascript" src="/js/angular-bootstrap.min.js"></script>
<script type="text/javascript" src="/js/app.js"></script>
<script type="text/javascript" src="/js/services.js"></script>
<script type="text/javascript" src="/js/controllers.js"></script>
<link rel="stylesheet" type="text/css" href="/css/styles.css" />
</head>
<body ng-app="IngredientsApp">
<ng-view></ng-view>
</body>
</html>
ingredients.html
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Existing Ingredients</th>
<th><input type="text" ng-model="descriptionFilter" placeholder="Search..."/></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="i in ingredientsList | filter: searchFilter">
<td>
<a href="/#/ingredient/{{i.Id}}">
{{i.Description}}
</a>
</td>
<td>Created at {{i.CreatedAt}}</td>
</tr>
</tbody>
</table>
ingredient.html
<script type="text/ng-template">
<div class="modal-header">
<h3 class="modal-title">I'm a modal!</h3>
</div>
<div class="modal-body">
{{ingredient.Description}}
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Dismiss</button>
</div>
</script>
controllers.js:
angular.module('IngredientsApp.controllers', []).controller('ingredientsController', function($scope, ingredientAPIservice) {
$scope.descriptionFilter = null;
$scope.ingredientsList = [];
$scope.searchFilter = function (ingredient) {
var keyword = new RegExp($scope.descriptionFilter, 'i');
return !$scope.descriptionFilter || keyword.test(ingredient.Description);
};
ingredientAPIservice.getIngredients().success(function (response) {
//Dig into the responde to get the relevant data
$scope.ingredientsList = response;
});
})
var ingredientController = function($scope, $routeParams, $modal, ingredientAPIservice) {
$scope.id = $routeParams.id;
$scope.ingredient = null;
ingredientAPIservice.getIngredient($scope.id).success(function (response) {
$scope.ingredient = response;
$scope.open = function (size) {
var modalInstance = $modal.open({
templateUrl: 'partials/ingredient.html',
controller: 'ingredientModalController',
size: size,
resolve: {
ingredient: function () {
console.log($scope.ingredient);
return $scope.ingredient;
}
}
});
}
});
}
var ingredientModalController = function($scope, $modalInstance, ingredient) {
$scope.ingredient = ingredient;
$scope.ok = function () {
$modalInstance.close($scope.ingredient);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}
I believe your issue is in app.js. Your route change causes the modal template (partials/ingredients.html) to be the only template displayed in ui-view. For the modal to work, you need to have the ingredients template nested within the ingredient template so both templates can be displayed at the same time. There are multiple ways to accomplish this.
If you are willing to give up the route change, just remove
when("/ingredient/:id", {templateUrl: "partials/ingredient.html", controller: "ingredientController"})
If you need the url to change, then I would look at doing it manually through the build in location service. https://docs.angularjs.org/guide/$location
You could just call a function that changes the url on click of an ingredient.

How to set up widget with Click to show Master/Slave Checkboxes in AngularJS

I'm attempting to write a prototype for a widget that contains 2 sides. On the left side is a list of interest groups, on the right side are the associated interest topics. (i.e. Pets on the left, Birds, Dogs, Cats, on the right). The data is populated by an AJAX call to an endpoint that's making a call to the Twitter API.
I'm not sure I'm approaching this correctly and would like some advice on how to get this set up the "Angular way". I was planning on using a similar approach to this JSFiddle for having the master/slave checkboxes setup. Below is my current code.
index.html
<!doctype html>
<html ng-app="interests">
<head>
<meta http-equiv="Content-type" content="text/html" charset="utf-8">
<title>Twitter Interests</title>
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="bower_components/fontawesome/css/font-awesome.min.css">
<link rel="stylesheet" content="text/css" href="stylesheets/style.css">
</head>
<body ng-controller="InterestController as interestCtrl">
<div class="container">
<div class="row">
<div class="col-xs-12">
<label>Interests</label>
<input type="text" ng-model="search.$">
</div>
<div class="col-xs-6">
<ul id="groups">
<li group-listing group="{{ group }}" ng-repeat="group in (groups | filter: search) track by $index">
</li>
</ul>
</div>
<div class="col-xs-6">
<div topic-listing topic="{{ topic }}" ng-repeat="topic in topics track by $index">
</div>
</div>
</div>
</div>
<script src="bower_components/angular/angular.min.js"></script>
<script src="bower_components/angular-route/angular-route.min.js"></script>
<script src="bower_components/underscore/underscore.js"></script>
<script src="javascripts/main.js"></script>
</body>
</html>
groupListing.html
<div ng-click="showTopics(group)">{{ group }}</div>
interestListing.html
<input type="checkbox" ng-model="topic.isChecked">{{ topic }}
main.js
var app = angular.module('interests', ['ngRoute']);
app.service('InterestService', ['$http', function ($http) {
var getInterests = function (query) {
return $http({
method: 'GET',
url: '/api/interests?=' + query
});
};
return {
getInterests: getInterests
}
}]);
app.controller('InterestController', ['$scope', 'InterestService', function ($scope, InterestService) {
var results = [];
var interests = {};
var resultArray;
var group;
var topic;
$scope.topics = [];
$scope.showTopics = function (group) {
$scope.topics = interests[group];
};
InterestService.getInterests().then(function (result) {
results = result.data.data;
_.each(results, function (result) {
resultArray = result.name.split('/');
group = resultArray[0];
topic = {};
topic.name = resultArray[1];
topic.isChecked = false;
if (_.has(interests, group)) {
interests[group].push(topic);
} else {
interests[group] = [];
interests[group].push({ name: 'All of ' + group, isChecked: false });
interests[group].push(topic);
}
});
$scope.groups = _.keys(interests);
});
}]);
app.directive('groupListing', function () {
return {
restrict: 'EA',
scope: {
group: "#"
},
controller: 'InterestController',
templateUrl: 'templates/groupListing.html'
}
});
app.directive('interestListing', function() {
return {
restrict: 'EA',
scope: {
topic: "#"
},
controller: 'InterestController',
templateUrl: 'templates/interestListing.html',
}
});

Resources