Reduce the code redundancy in angularjs function - angularjs

I am a calling function two time (I think which is not necessary) so how I can reduce the code so that my application performance will improve.
This is my code:
<!DOCTYPE html>
<html lang="en" ng-app="demo">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<script src="jq.js"></script>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
<title>find freelancer..</title>
</head>
<body>
<div ng-controller="myCtrl">
Experence Level: <br>
Entry level:<input type="checkbox" ng-click="myClick()">
<div ng-repeat="data in people">
{{data.name}}
</div>
</div>
<div ng-controller="myCtrl1">
Intermediate level:<input type="checkbox" ng-click="myClick1()">
<div ng-repeat="data in people">
{{data.sname}}
</div>
</div>
<script>
var app=angular.module('demo',[]);
app.controller('myCtrl',function($scope,$http)
{
$scope.myClick=function(event) {
$http.get("image.json")
.success(function(response){
$scope.people=response.jsonrecords;
});
}
});
app.controller('myCtrl1',function($scope,$http)
{
$scope.myClick1=function(event) {
$http.get("image.json")
.success(function(response){
$scope.people=response.jsonrecords;
});
}
});
</script>
</body>
</html>

As you are using same ajax request then it can be a proper candidate for making it a service/factory:
app.factory ('imgdata', ['$http', function(){
var result = $http.get('urlhere');
return result; // <--return it here.
});
Now imgdata can be injected:
app.controller('myCtrl',['$scope', 'imgdata', function($scope, imgdata){
$scope.myClick=function(event) {
imgdata.then(function (resp){
$scope.people = resp.data;
});
};
});
Same goes for other controller.

I think this is your target.. i hope helps you
var app = angular.module('demo', []);
app.controller('myCtrl', function($scope, appService) {
$scope.myClick = function(event) {
if ($scope.checkbox1) {
appService.get().success(function(response) {
//$scope.people = response;
});
} else {
$scope.people = [];
}
}
});
app.controller('myCtrl1', function($scope, appService) {
$scope.myClick1 = function(event) {
if ($scope.checkbox2) {
appService.get().success(function(response) {
//$scope.people = response;
});
} else {
$scope.people = [];
}
}
});
app.service("appService", function($http) {
this.get = function() {
return http({
url: "image.json",
method: "GET",
headers: {
'Content-Type': "application/json"
},
async: true
});
}
this.post = function() {
return http({
data: "////",
url: "url",
method: "POST",
headers: {
'Content-Type': "application/json"
},
async: true
});
}
//and .... edit .. delete
});
<!doctype html>
<html ng-app="demo">
<head>
</head>
<body>
<div ng-controller="myCtrl">
Entry level:
<input type="checkbox" ng-model="checkbox1" ng-change="myClick()">
<div ng-repeat="data in people">
{{data.name}}
</div>
</div>
<div ng-controller="myCtrl1">
Intermediate level:
<input type="checkbox" ng-model="checkbox2" ng-change="myClick1()">
<div ng-repeat="data in people">
{{data.name}}
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-rc.0/angular.js"></script>
</body>
</html>

Depending on how you might use it later, but for the moment I would create a service looking a bit like this
app.factory('getPeople', function($http) {
return function($scope) {
return function(event) {
$http.get('image.json').success(function(response) {
$scope.people = response.jsonrecords;
});
};
};
});
Then your controller is dead simple
app.controller('myCtrl',function($scope, getPeople) {
$scope.myClick = getPeople($scope);
});

Related

Get autocompleted value from input in controller

I have the following in my view:
<label for="txtFrom">Pickup Location</label>
<input type="text" id="pickup" placeholder="Address, aiport, train station, hotel..." ng-model="pickup">
<label for="txtDestination">Destination</label>
<input type="text" id="destination" placeholder="Address, aiport, train station, hotel..." ng-model="destination">
<input class="btn btn-success" name="calcPrice" id="calcPrice" type="submit" value="Calculate Price" ng-click="calcPrice()">
I am using google maps api for places to autocomplete the input boxes, so if a user starts typing "Lo", he will get a list of places that starts with "Lo" and for example he chooses London.
The problem is in my controller I am not getting the whole autocompleted value. I am only getting what the user initially entered, in this case "Lo".
Here is my controller:
app.controller('BookingsCtrl', function($scope, BookingsService) {
$scope.pickup = "";
$scope.destination = "";
$scope.syncNotification = "";
$scope.calcPrice = function() {
console.log($scope.pickup);
BookingsService.save({
pickup: $scope.pickup,
destination: $scope.destination
}, function(response) {
console.log(response.message);
});
};
});
EDIT:
Here is also a snippet of the JS:
var pickup = document.getElementById('pickup');
var options = {
componentRestrictions: {
country: 'ee'
}
};
var autocompletePickup = new google.maps.places.Autocomplete(pickup, options);
google.maps.event.addListener(autocompletePickup, 'place_changed', function () {
var place = autocompletePickup.getPlace();
pickup.innerHtml = place.formatted_address;
var lat = place.geometry.location.lat();
var long = place.geometry.location.lng();
});
EDIT 2 : Added service
app.service('BookingsService', function ($resource) {
return $resource('http://localhost:3000/', {});
});
EDIT 3 : Template
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="components/bootstrap/dist/css/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="assets/css/style.css" type="text/css" />
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDt1Y30OssBToIzSCOr3g5IkN3c0D75XVE&libraries=places"
></script>
</head>
<body ng-app='strelsau_client'>
<div class="site-wrapper">
<div class="site-wrapper-inner">
<div class="cover-container">
<div class="masthead clearfix">
<div class="inner">
<img class="masthead-brand" src="../assets/img/logo.png">
<nav>
<ul class="nav masthead-nav">
<li class="active">Home</li>
<li>Contact</li>
</ul>
</nav>
</div>
</div>
<div ng-view>
</div>
</div>
</div>
</div>
<script src="components/jquery/dist/jquery.min.js"></script>
<script src="components/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="components/angular/angular.min.js"></script>
<script src="components/angular-route/angular-route.min.js"></script>
<script src="components/angular-resource/angular-resource.min.js"></script>
<script src="js/main.js"></script>
<script src="js/controllers/bookings_controllers.js"></script>
<script src="js/services/bookings_service.js"></script>
</body>
</html>
In fact pickup input element is not getting updated once the place is resolved.
The problem with this function:
google.maps.event.addListener(autocompletePickup, 'place_changed', function () {
var place = autocompletePickup.getPlace();
pickup.innerHtml = place.formatted_address; //invalid
//...
});
For setting input field value should be used value property.
Anyway, given the example, try to replace it with:
(function (scope) {
google.maps.event.addListener(autocompletePickup, 'place_changed', function () {
var place = autocompletePickup.getPlace();
scope.pickup = place.formatted_address;
});
})($scope);
Example
angular.module('myApp', [])
.controller('BookingsCtrl', function ($scope) {
$scope.pickup = "";
$scope.destination = "";
$scope.syncNotification = "";
var pickup = document.getElementById('pickup');
var options = {
componentRestrictions: {
country: 'ee'
}
};
var autocompletePickup = new google.maps.places.Autocomplete(pickup, options);
(function (scope) {
google.maps.event.addListener(autocompletePickup, 'place_changed', function () {
var place = autocompletePickup.getPlace();
scope.pickup = place.formatted_address;
});
})($scope);
$scope.calcPrice = function () {
console.log($scope.pickup);
alert($scope.pickup);
/*BookingsService.save({
pickup: $scope.pickup,
destination: $scope.destination
}, function (response) {
console.log(response.message);
});*/
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div ng-app="myApp" ng-controller="BookingsCtrl" ng-cloak>
<label for="txtFrom">Pickup Location</label>
<input type="text" id="pickup" placeholder="Address, aiport, train station, hotel..." ng-model="pickup">
<label for="txtDestination">Destination</label>
<input type="text" id="destination" placeholder="Address, aiport, train station, hotel..." ng-model="destination">
<input class="btn btn-success" name="calcPrice" id="calcPrice" type="submit" value="Calculate Price" ng-click="calcPrice()">
</div>

AngularJs doesn't work if I give a value to ng-app and ng-controller

I hope you may help me.
I'm quite new with Angular so I'm maybe making some stupid error but, when a give a value to ng-app, it doesn't work AngularJs.
I make here an example:
This is my home.html that doesn't work (when I say "doesn't work" I mean that I see printed "{{name}}" instead of its value).
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script>
var req={
method: 'POST',
url: 'http://localhost:8080/ConnectionDb/WebAppDbServlet',
data: {"nome":$scope.name}
}
var app=angular.module('noteApp', [])
app.controller('noteCtrl', function ($scope, $http){
$scope.addNote = function () {
$http(req).success(function(data, status, headers, config) {
$scope.nome = data;
}).error(function(data, status, headers, config) {
});
}
})
</script>
</head>
<body ng-app="noteApp">
<div ng-controller="noteCtrl">
<form>
<div>
Insert your name: <input type="text" name="name" data-ng-model="name"><br>
</div>
</form>
<p>Hola {{name}}</p>
</div>
</body>
</html>
but if I change it like this
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script>
var req={
method: 'POST',
url: 'http://localhost:8080/ConnectionDb/WebAppDbServlet',
data: {"nome":$scope.name}
}
var app=angular.module('noteApp', [])
app.controller('noteCtrl', function ($scope, $http){
$scope.addNote = function () {
$http(req).success(function(data, status, headers, config) {
$scope.nome = data;
}).error(function(data, status, headers, config) {
});
}
})
</script>
</head>
<body ng-app>
<div>
<form>
<div>
Insert your name: <input type="text" name="name" data-ng-model="name"><br>
</div>
</form>
<p>Hola {{name}}</p>
</div>
</body>
</html>
it goes perfectly as it should.
Any suggestion?
In your view you are using {{ name }} but inside of your controller you are putting the data inside of $scope.nome.
Just change $scope.nome > $scope.name
You are setting the req variable using $scope.name but at that point scope is not defined. If you open the console you will see an error about. Try this:
http://plnkr.co/edit/LqZNX8BYnCnbUD29YRfi?p=preview
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script>
var req={
method: 'POST',
url: 'http://localhost:8080/ConnectionDb/WebAppDbServlet',
}
var app=angular.module('noteApp', [])
app.controller('noteCtrl', function ($scope, $http){
$scope.addNote = function () {
req.data={"nome":$scope.name};
$http(req).success(function(data, status, headers, config) {
$scope.name = data;
}).error(function(data, status, headers, config) {
});
}
})
</script>
</head>
<body ng-app="noteApp">
<div ng-controller="noteCtrl">
<form>
<div>
Insert your name: <input type="text" name="name" data-ng-model="name"><br>
</div>
</form>
<p>Hola {{name}}</p>
</div>
</body>
</html>
the wrong variable name ("nome" instead of "name") is unrelated to your issue but it still need to be corrected
You are missing a " ; " after "var app=angular.module('noteApp', [])" so noteApp is not getting initialized.

angularjs: how to link to service.js file in template file

I have currently included all service files and controller files in index.html in my angularJS application and it is working fine.
But I want to include the respective service file and controller file in the template file, so that unwanted files for the home page of my application will not be loaded in the initial load: thus decreasing the time to load the home page.
I have tried to do this, but the I could not get the json data from the service.
Here is what I have done so far
app.js
var app = angular.module('app', ['ngRoute'])
.config(function ($routeProvider, $locationProvider) {
$routeProvider.when('/books',
{
templateUrl:'app/templates/books.html',
controller:'booksController'
}).when('/games',
{
templateUrl: 'app/templates/games.html',
controller: 'gamesController'
});
$locationProvider.html5Mode(true);
});
eventData.js service file
app.factory('eventData', function ($http, $log, $q) {
return {
getEvent: function () {
var deferred = $q.defer();
$http({
method: 'GET', url: 'https://www.googleapis.com/books/v1/volumes?q=harry%20potter'
}).success(function (data, status, headers, config) {
deferred.resolve(data);
}).error(function (data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
},
getGames: function () {
var deferred = $q.defer();
$http({
method: 'GET', url: 'https://www.googleapis.com/books/v1/volumes?q=hunger%20games'
}).success(function (data, status, headers, config) {
deferred.resolve(data);
}).error(function (data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
}
};
});
eventController.js
'use strict';
app.controller("EventController", function EventController($scope,eventData) {
$scope.event = eventData.getEvent();
$scope.event.then(function(event) {
console.log(event);
$scope.items = event.items;
console.log($scope.items);
},function(status) {
console.log(status);
});
});
BooksController.js
'use strict';
app.controller("booksController", function booksController($scope, eventData) {
$scope.event = eventData.getEvent();
$scope.event.then(function (event) {
console.log(event);
$scope.items = event.items;
console.log($scope.items);
}, function (status) {
console.log(status);
});
});
books.html
<script src="app/controllers/eventController.js"></script>
<script src="app/controllers/booksController.js"></script>
<script src="app/services/eventData.js"></script>
<div style="padding-left: 20px;padding-right: 20px">
<div class="row">
<h3>Sessions</h3>
<ul style="list-style-type: none;">
<li ng-repeat="session in items">
<div class="row session">
<div class="well col-md-12">
<h4 class="well">{{session.volumeInfo.title}}</h4>
<h6 style="margin-top: -10px">{{session.volumeInfo.publishedDate}}</h6>
<span>Page Count: {{session.volumeInfo.pageCount}}</span><br />
<span>Authors: {{session.volumeInfo.authors}}</span>
<p>{{session.searchInfo.textSnippet}}</p>
</div>
</div>
</li>
</ul>
</div>
</div>
index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<title>Airlines!</title>
<link href="Content/bootstrap.css" rel="stylesheet" />
<meta charset="utf-8">
<base href="/airlines/">
</head>
<body>
<div class="container">
<div class="navbar">
<div class="navbar-inner">
<ul class="nav">
<li>Harry Potter</li>
<li>Hunger Games</li>
</ul>
</div>
</div>
<ng-view></ng-view>
</div>
<link href="Content/bootstrap.min.css" rel="stylesheet" />
<script src="Scripts/angular.js"></script>
<script src="Scripts/angular-route.js"></script>
<script src="app/app.js"></script>
</body>
</html>
Can you identify what I am doing wrong?

angular js not waiting for rest response

I am new to angular js. I have to work with the rest calls in java. I have taken an example related to angularjs, java rest.
see app.js
angular.module('ngdemo', ['ngRoute','ngdemo.filters', 'ngdemo.services', 'ngdemo.directives', 'ngdemo.controllers']).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/user-list', {templateUrl: 'partials/user-list.html', controller: 'UserListCtrl'});
$routeProvider.when('/user-detail/:id', {templateUrl: 'partials/user-detail.html', controller: 'UserDetailCtrl'});
$routeProvider.when('/user-creation', {templateUrl: 'partials/user-creation.html', controller: 'UserCreationCtrl'});
}]);
controllers.js
'use strict';
/* Controllers */
var app = angular.module('ngdemo.controllers', []);
app.run(function ($rootScope, $templateCache) {
$rootScope.$on('$viewContentLoaded', function () {
$templateCache.removeAll();
});
});
app.controller('UserListCtrl', ['$scope', 'UsersFactory', 'UserFactory', 'DeleteUserFactory', 'UsersSearchFactory', '$location',
function ($scope, UsersFactory, UserFactory, DeleteUserFactory, UsersSearchFactory, $location) {
// callback for ng-click 'editUser':
$scope.editUser = function (userId) {
$location.path('/user-detail/' + userId);
};
$scope.searchUser = function () {
$scope.users = UsersSearchFactory.search($scope.user);
};
// callback for ng-click 'deleteUser':
$scope.deleteUser = function (user) {
DeleteUserFactory.delete(user);
$scope.users = UsersFactory.query({startRow: 0}, {endRow: 75});
};
// callback for ng-click 'createUser':
$scope.createNewUser = function () {
$location.path('/user-creation');
};
$scope.users = UsersFactory.query({startRow: 0}, {endRow: 75});
}]);
app.controller('UserDetailCtrl', ['$scope', '$routeParams', 'UserFactory', 'UpdateUserFactory', '$location',
function ($scope, $routeParams, UserFactory, UpdateUserFactory, $location) {
// callback for ng-click 'updateUser':
$scope.updateUser = function () {
UpdateUserFactory.update($scope.user);
$location.path('/user-list');
};
// callback for ng-click 'cancel':
$scope.cancel = function () {
$location.path('/user-list');
};
$scope.user = UserFactory.show({id: $routeParams.id});
}]);
app.controller('UserCreationCtrl', ['$scope', 'CreateUserFactory', '$location',
function ($scope, CreateUserFactory, $location) {
// callback for ng-click 'createNewUser':
$scope.createNewUser = function () {
CreateUserFactory.create($scope.user);
$location.path('/user-list');
}
}]);
services.js
'use strict';
/* Services */
var services = angular.module('ngdemo.services', ['ngResource']);
services.factory('UsersFactory', function ($resource) {
return $resource('/ngdemo/rest/getUsers/:startRow/:endRow', {}, {
query: { method: 'GET', isArray: true, params: {startRow: '#startRow', endRow: '#endRow'} },
create: { method: 'POST' }
})
});
services.factory('UsersCountFactory', function ($resource) {
return $resource('/ngdemo/rest/getUsersCount', {}, {
count: { method: 'GET'}
})
});
services.factory('UsersSearchFactory', function ($resource) {
return $resource('/ngdemo/rest/searchUser', {}, {
search: { method: 'POST', isArray: true, }
})
});
services.factory('CreateUserFactory', function ($resource) {
return $resource('/ngdemo/rest/registerUser', {}, {
create: { method: 'POST' }
})
});
services.factory('UpdateUserFactory', function ($resource) {
return $resource('/ngdemo/rest/updateUser', {}, {
update: { method: 'POST' }
})
});
services.factory('DeleteUserFactory', function ($resource) {
return $resource('/ngdemo/rest/deleteUser', {}, {
delete: { method: 'POST' }
})
});
services.factory('UserFactory', function ($resource) {
return $resource('/ngdemo/rest/findUserById/:id', {}, {
show: { method: 'GET' }
})
});
user-list.html
<div class="container">
<form novalidate="novalidate" class="form-horizontal">
<div class="control-group">
<label class="control-label" for="inputFirstName">First name:</label>
<div class="controls">
<input type="text" id="inputFirstName" ng-model="user.firstName" placeholder="First name"/>
</div>
</div>
<div class="form-group">
<div class="controls">
<a ng-click="searchUser()" class="btn btn-primary btn-xs">Search</a>
</div>
</div>
</form>
</div>
<div class="span6">
<table class="table table-striped table-condensed" >
<thead>
<tr>
<th style="min-width: 80px;"> First Name</th>
<th style="min-width: 80px;"> Last Name</th>
<th style="width:20px;"> </th>
<th style="width:20px;"> </th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users" > <!-- | orderBy:sort.sortingOrder:sort.reverse" > -->
<td>{{ user.firstName }}</td>
<td>{{ user.lastName }}</td>
<td><a ng-click="editUser(user.userId)" class="btn btn-small btn-primary">edit</a></td>
<td><a ng-click="deleteUser(user)" class="btn btn-small btn-danger">delete</a></td>
</tr>
</tbody>
</table>
<a ng-click="createNewUser()" class="btn btn-small">create new user</a>
</div>
index.html
<!doctype html>
<html lang="en" ng-app="ngdemo">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ngdemo app</title>
<link rel="stylesheet" href="css/app.css"/>
<link rel="stylesheet" href="css/bootstrap/bootstrap-responsive.min.css"/>
<link rel="stylesheet" href="css/bootstrap/bootstrap.min.css"/>
</head>
<body>
<ul class="menu">
<li>user-list</li>
</ul>
<div ng-view></div>
<!-- JQuery ================================================================ -->
<script src="js/jquery/jquery-2.0.3.js"></script>
<!-- Bootstrap ============================================================= -->
<script src="js/bootstrap/bootstrap.js"></script>
<script src="lib/angular/angular.js"></script>
<script src="lib/angular/angular-resource.js"></script>
<script src="lib/angular/angular-route.js"></script>
<!-- AngularJS App Code ==================================================== -->
<script src="js/app.js"></script>
<script src="js/services.js"></script>
<script src="js/controllers.js"></script>
<script src="js/filters.js"></script>
<script src="js/directives.js"></script>
</body>
</html>
Question:
I am getting the rest call to server and it is sending the response.
When i open index.html it is displaying the out put on the page. When i click on edit(update) or delete buttons or create new user button, the user details are saved in the database but the changed data is not displayed on the table.
This is happened because after editing(updating) , deleting and creating new user the angular code is not waiting for the response from REST call. It immediately calls the $location.path('/user-list'); So old data is displayed in the table.
Please help me.
I have added the success call backs for all the methods update, create, delete as
$scope.createNewUser = function () {
CreateUserFactory.create($scope.user, function(response) {
$location.path('/user-list');
});
}

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