Combine many array values to related array vlaue with Angularjs - angularjs

I have been working with Angularjs for a few weeks now and am starting to LOVE it, but I have one last problem to solve that has alluded me...
Basically I have two json files with related values.. meaning there is one common key in each json file that I want to use to do what in SQL would be a join of sorts.. This is a one to many relationship. So one value related to multiple values. I'm close but I just can't seem to figure out how to say "for this array value, grab all of these related values from this other file then display them as one result".
I've also included Underscorejs and injected it into my controller as a possible way to solve this as well..
I'm not familiar enough yet to figure this out but here is my code so far:
Contents of the ab_activities.json (the file with the "many"):
[
{
"unique_id":"001",
"state":"NY",
"state_id":"1.S2.3a"
},
{
"unique_id":"001",
"state":"NY",
"state_id":"1.S3.2d"
},
{
"unique_id":"001",
"state":"FL",
"state_id":"SC.4.N.1.D"
}
]
Contents of the ee_activities.json file (the "one" related value):
[
{
"unique_id":"001",
"title":"Some Title",
"url_title":"some-title"
}
]
Angular code:
var underscore = angular.module('underscore', []);
underscore.factory('_', function() {
return window._;
});
var abApp = angular.module('abApp', ['underscore']);
abApp.factory('abData', function($http, $q) {
var deffered = $q.defer();
var data = [];
var abData = {};
abData.async = function() {
$http.get('/data/ab_activities.json')
.success(function(ab) {
data = ab;
deffered.resolve();
});
$http.get('/data/ee_activities.json')
.success(function(ee) {
data = ee;
//deffered.resolve();
});
return deffered.promise;
};
abData.data = function() {
return data;
};
return abData;
});
abApp.controller("abEE", function(abData, $scope) {
var abApp = this;
abData.async().then(function(d) {
abApp.subjects = abData.data();
});
})
And HTML:
<div ng-controller="abEE as ee">
<p ng-repeat="subject in ee.subjects">
<strong>{{subject.title}}</strong>
<ul>
<li ng-repeat="???">{{subject.state}}, {{subject.state_id}}</li>
</ul>
</p>
</div>
And finally - What I'm hoping to achieve:
Title: Some Title
NY, 1.S2.3a
NY, 1.S3.2d
FL, SC.4.N.1.D
The {{subject.state}} / {{subject.state_id}} are the many related values.. and I'm trying to relate the results by the "unique_id".
Right now the interesting thing that is happening is that there is one value from the ab_activities.json file that is being displayed multiple times because deffered.resolve(); is set on the ee_activities.json values and that is the one that has the "many to one" values.
I'm thinking that I can use a "forEach()" function then somehow pass the value that I want to relate back, then use underscore's ._where() function to get the related values?? Just not sure yet, hopefully someone will have some Angular code brilliance that can help out :-)

you are making it very complex through your existing code. its very simple to implement. I'm providing you fiddle. go through it carefully.
here is fiddle link
First of all, in this fiddle i'm using your json objects directly without making any server trip. so you have to manage, when you are modifying your code, on your own.
This will help you a lot to learn new thing...(its very easy)
I'm showing you dynamic way to bind data conditionally as per your requirement.
now if you have more data, angular will manage on its own...
html page.
<html ng-app>
<div ng-controller="ctrl">
<div ng-repeat="title in titles">
<div>{{title.title}}</div>
<div ng-repeat="state in states|filter:{unique_id:title.unique_id}">
<div >{{state.state}}{{state.state_id}}</div>
</div>
</div>
<div>
</html>
your controller .js file
function ctrl($scope) {
$scope.states = [
{
"unique_id":"001",
"state":"NY",
"state_id":"1.S2.3a"
},
{
"unique_id":"001",
"state":"NY",
"state_id":"1.S3.2d"
},
{
"unique_id":"001",
"state":"FL",
"state_id":"SC.4.N.1.D"
}
];
$scope.titles = [
{
"unique_id":"001",
"title":"Some Title",
"url_title":"some-title"
}
];
}
EDITED:
Updated fiddle according to your existing html page in here

Related

Angular-DataTables custom filter

I am trying to add a custom filter to angular-DataTables with server side processing, which works perfectly with sorting and built in search of datatables.
I was following example Angular-DataTables, to build the server side processing and setup the DataTable, in searching around i have found some info but haven't been able to make it work.
What i am trying to get is to redraw the table with filtered data once the checkbox [Player] has been triggered.
Does anyone know a solution for this or has a working example for this?
have found this example Custom Table Filter, but it seems it doesn't work either.
HTML:
<div ng-app="showcase"><div ng-controller="ServerSideProcessingCtrl">
<label><input type="checkbox" id="customFilter" value="player"> Player</label>
<table datatable="" dt-options="dtOptions" dt-columns="dtColumns" class="row-border hover"></table>
JS part:
'use strict';
angular.module('showcase', ['datatables'])
//.controller('ServerSideProcessingCtrl', ServerSideProcessingCtrl);
.controller('ServerSideProcessingCtrl',["$scope", "DTOptionsBuilder", "DTColumnBuilder", function($scope, DTOptionsBuilder, DTColumnBuilder) {
//function ServerSideProcessingCtrl(DTOptionsBuilder, DTColumnBuilder) {
console.log($scope);
$scope.dtOptions = DTOptionsBuilder.newOptions()
.withOption('ajax', {
// Either you specify the AjaxDataProp here
// dataSrc: 'data',
url: 'getTableData.php',
type: 'POST'
})
// or here
.withDataProp('data')
.withOption('serverSide', true)
.withPaginationType('full_numbers');
$scope.dtColumns = [
DTColumnBuilder.newColumn('id').withTitle('ID'),
DTColumnBuilder.newColumn('name').withTitle('First name'),
DTColumnBuilder.newColumn('position').withTitle('Position'),
DTColumnBuilder.newColumn('type').withTitle('Type')
];
$scope.$on('event:dataTableLoaded', function(event, loadedDT) {
console.log(event);
console.log(loadedDT);
$('#customFilter').on('change', function() {
loadedDT.DataTable.draw();
} );
});
}]);
JSON on load:
{"draw":"1","recordsTotal":8,"recordsFiltered":8,"data":[{"id":"1","name":"Raul","position":"front","type":"player"},{"id":"2","name":"Crespo","position":"front","type":"player"},{"id":"3","name":"Nesta","position":"back","type":"player"},{"id":"4","name":"Costacurta","position":"back","type":"player"},{"id":"5","name":"Doc Brown","position":"staff","type":"medic"},{"id":"6","name":"Jose","position":"staff","type":"manager"},{"id":"7","name":"Ferguson","position":"staff","type":"manager"},{"id":"8","name":"Zinedine","position":"staff","type":"director"}]}
After searching and browsing, combined few examples and came up with this.
HTML :
<label><input type="checkbox" id="customFilter" value="player" ng-click="reload()" > Player</label>
JS:
'use strict';
angular.module('showcase', ['datatables'])
//.controller('ServerSideProcessingCtrl', ServerSideProcessingCtrl);
.controller('ServerSideProcessingCtrl',["$scope", "DTOptionsBuilder", "DTColumnBuilder","DTInstances", function ($scope, DTOptionsBuilder, DTColumnBuilder, DTInstances) {
//function ServerSideProcessingCtrl(DTOptionsBuilder, DTColumnBuilder) {
console.log($scope);
$scope.dtOptions = DTOptionsBuilder.newOptions()
.withOption('ajax', {
// Either you specify the AjaxDataProp here
// dataSrc: 'data',
url: 'getTableData.php',
type: 'POST',
// CUSTOM FILTERS
data: function (data) {
data.customFilter = $('#customFilter').is(':checked');
}
})
// or here
.withDataProp('data')
.withOption('serverSide', true)
.withPaginationType('full_numbers');
$scope.dtColumns = [
DTColumnBuilder.newColumn('id').withTitle('ID'),
DTColumnBuilder.newColumn('name').withTitle('First name'),
DTColumnBuilder.newColumn('position').withTitle('Position'),
DTColumnBuilder.newColumn('type').withTitle('Type')
];
DTInstances.getLast().then(function (dtInstance) {
$scope.dtInstance = dtInstance;
});
$scope.reload = function(event, loadedDT) {
$scope.dtInstance.reloadData();
};
}]);
and on the backend just go through the $_POST and check for custom filter, hopefully this will help someone
You can use withFnServerData with fromSource functions instead of
withOption:
This API allows you to override the default function to retrieve the data (which is $.getJSON according to DataTables documentation) to something more suitable for you application.
It's mainly used for Datatables v1.9.4. See DataTable documentation.
$scope.dtOptions = DTOptionsBuilder.fromSource('data.json')
.withFnServerData(serverData);
function serverData (sSource, aoData, fnCallback, oSettings) {
oSettings.jqXHR = $.ajax({
'dataType': 'json',
'type': 'POST',
'url': sSource,
'data': aoData,
'success': fnCallback
});
:)
Ok sorry its not a full blown example. This only works with angular and datatables, if you do a filter on the ng-repeat eg | aFilter:this The this transfers the scope. The filtering applied can now be quite complex. Within the ng-controller <div> you can have an html partial containing drop downs or input texts, all having an ng-model value.
When these change they kick off the filter routineaFilter an angular.filter('aFilter'.... js routine. The records are piped through the afilter routine allowing the ones wanted to be pushed onto an array and this is what is returned with the return. It doesn't work with breeze, yet. Be aware it is unlikely to be server side. To deal with server side maybe an SQL call in the service....another day.
eg in the ng-table id="test" :
<tr ng-repeat="edRec in aSetOfJSonRecords | aFilter:this | orderBy:'summat'">
{{edRec.enCode}} etc
</tr>
in the aFilter, the fltEnCode represents the ng-model values, the test variable allows freedom from nulls causing issues upon comparison, good idea to test for undefined first:
app.filter('aFilter', [function () {
return function (items, $scope) {
var countItems = 0;
var filtered = [];
var isOK = 0;
angular.forEach(items, function (item) {
isOK = 1;
// some conditions
if ($scope.fltEnCode !== "") {
if (item.enCode === null) { test = ""; } else { test = item.enCode; }
if (test.indexOf($scope.fltEnCode) < 0) isOK = 0;
}
// end of conditions
if (isOK > 0) {
filtered.push(item);
countItems++;
}
});
// alert(countItems);
return filtered;
};
}]);
Hope its of some use. I've avoided boolean variables as they have given grief before. Odd occasions have needed an ng-change in the html items pointing to an angular function resetting the data by calling the getTheItemsForTest() in the controller. This redraws the list. Having
$scope.dtOptions = {
stateSave: false, .......
in your controller, keeps the sorting columns correct.
$(document).ready(function() {
var table = $('#test').DataTable();
table.draw();
};
might also be useful if its recalcitrant. I need to know how to make it work for breeze??? Enjoy..
here is what I really missed after I searched alot
bower install datatables-light-columnfilter

Angularjs trying to watch a property of an object in an array

$scope.testObj = [{'name':'john'},{'name':'bob'}];
In this case I do
$scope.watch(testObj.name, examplefunction, true)....
this does not work but this does
$scope.watch(testObj[0].name...)
The former stops the page from completely loading, am I doing this wrong? I read a bunch of stackoverflow examples that used the same syntax. Basically what I am trying to accomplish is to save the object to the database before sending it off to another module, when a user finishes editing a certain cell in ng-grid(name in this example).
This was solved here. See if this works for you.
http://blogs.microsoft.co.il/choroshin/2014/03/26/angularjs-watch-for-changes-in-specific-object-property/
Here is a JSFiddle with example
var app=angular.module('App', []);
function ctrl($scope){
$scope.count=0;
$scope.people = [{id:1,name: "bill"}, {id:2,name: "jim"}, {id:3,name: "ryan"}]
$scope.$watch(function($scope) {
return $scope.people.
map(function(obj) {
return obj.name
});
}, function (newVal) {
$scope.count++;
$scope.msg = 'person name was changed'+newVal;
}, true);
}
http://jsfiddle.net/byws7/28/

AngularJS: Trying to make filter work with delayed data

I have this html:
<div ng-app='myApp'>
<div ng-controller='testCtrl'>
<h3>All possesions</h3>
{{possessions}}
<h3>Green cars</h3>
{{greenishCars}}
</div>
</div>
And this script:
angular.module('myApp', [])
.factory('getPossessionsService', ['$timeout',
function($timeout) {
var possessions = {};
$timeout(function() {
possessions.cars = [{
model: "Mazda 6",
color: "lime green"
}, {
model: "Audi A3",
color: "red"
}, {
model: "Audi TT",
color: "green"
}, {
model: "Volkswagen Lupo",
color: "forest green"
}];
possessions.jewelry = [{
type: "ring",
metal: "gold"
}, {
type: "earring",
metal: "silver"
}];
}, 1000);
return possessions;
}
])
.controller('testCtrl', ['$scope', 'filterFilter', 'getPossessionsService',
function($scope, filterFilter, getPossessionsService) {
$scope.possessions = getPossessionsService;
$scope.greenishCars = filterFilter($scope.possessions.cars, carColorIsGreenShade);
function carColorIsGreenShade(car) {
return ['green', 'forest green', 'lime green'].indexOf(car.color) != -1;
}
}
]);
I am trying to get $scope.greenishCars to update correctly when the data is available, but it is not. I understand that this has because $scope.possessions.cars is an array and therefore not a reference to the data, so it is not updated. But how should I alter my script so that greenishCars get updated when the data arrives? I am guessing I should use $scope.possessions "directly", but I do not quite see how I should rewrite this nicely....
See this plunk.
Edit: Thoughts on which answer to choose
As in comments in the answers to Oliver and MajoB, I ended up with using both filter and watch. In my special case the request for the data was made in another place (not in the controller of my page in question), so it was not so easy to act on the resolving of the promise (with promise.then as suggested by Oliver), I therefore used a watch. But there is a couple of things to be aware of with watches. If the variable you want to watch is not on the scope, then you must provide the variable by returning it from a function. And if you want to watch for a change in an existing property (say somebody repaints my existing Mazda 6 in a different color), then none of the watch-answers works, as you need to add "true" when calling $watch. When you add 'true' as the second paramenter to $watch, then it watches for changes in the actual values of the variable, and it also does this check for values deeply in an object/array (without it just checks references, see this blog). I ended up with this controller/$watch for my real-life use-case (which is a little bit different that in my example above, and is based on Olivers filter-plunk), and it looks like this (changed to fit the plunk):
.controller('testCtrl', ['$scope', 'greenFilter', 'getPossessionsService',
function($scope, greenFilter, getPossessionsService) {
var none-scope-possessions = getPossessionsService; // I do not want to expose all properties on the scope....
$scope.greenishCars = [];
$scope.$watch(function() {return none-scope-possessions.cars}, function(newValue){
if (newValue) {
$scope.greenishCars = greenFilter(newValue);
}
},true);
}
]);
You can watch the data changes:
$scope.$watch('possessions.cars', function(){
$scope.greenishCars = filterFilter($scope.possessions.cars, carColorIsGreenShade);
});
I would recommend just building your own custom filter like so:
.filter('green', function() {
return function(possessions) {
if (!possessions) return null;
var filtered = [];
angular.forEach(possessions, function(possesion){
if (['green', 'forest green', 'lime green'].indexOf(possesion.color) != -1) {
filtered.push(possesion);
}
});
return filtered;
};
})
Then pass your collection through that filter like so:
<div ng-controller='testCtrl'>
<h3>All possesions</h3>
{{possessions}}
<h3>Green cars</h3>
{{possessions.cars|green}}
</div>
Everything else will happen automatically. See the updated plunkr.
You can watch possesions collection for changes:
$scope.$watchCollection('possessions', function (newValue) {
if (newValue)
{
$scope.greenishCars = filterFilter(newValue.cars, carColorIsGreenShade);
}
});
http://plnkr.co/edit/Sl6dW0pqKr593OXrgDb9?p=preview
First thing is , var possessions = {}; you have declared an object , cars is an field in this object , which has array of cars . so either return possessions.cars or in the markup call it via possessions.cars[0].. if you want to call only one value ..or if you want to display all the values the use ng-repeat=" car in possessions.cars" .

Saving data with updated values in Backbone.js

I am working on MVC application with Backbone.js.
Assuming, I have a View of User details:-
var userDetailsView = Backbone.View.extend({
model: userModel,
el: "#userDteails",
template: Handlebars.templtas.userDetails
initialize: function () {
this.model = new userModel();
this.model.fetch({
success: function (data) {
this.render();
}
});
},
render: function () {
$(this.el).html(this.template());
},
events: {
"", "saveUserDetails" //event for save
},
saveUserDetails: function () {
//How do I get the update value of FirstName??
}
});
Now, in similar line I have a handlebar template which deals with edit details of User Model.
<div id="userDetails">
<input type="text" value="{{FirstName}}" id="firstName"/>
</div>
Please ignore the code mistakes as its just a dummy code, now if I need to save the user details(say for eg. FirstName). Then how do I get the updated value?
Should it be:-
saveUserDetails: function () {
//How do I get the update value of FirstName??
this.model.set("", $('#Firstname').val());
}
or should I follow converting form data to JSON, and update my this.model i.e create my HTML markup with name attribute:-
<form>
First Name:<input type="text" name="Fname" maxlength="12" size="12"/> <br/>
</form>
and use the function suggested by Tobias Cohen
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
and do :-
$('form').submit(function() {
$('#result').text(JSON.stringify($('form').serializeObject()));
return false;
});
I am not an expert in Backbone, but have seen at-least 10-15 samples and tutorials which teach backbone. Out of those I found the above two way to do it.
Please let me know, what would be best way to proceed.
Both ways are OK! It depends on how complex your HTML <-> Model mapping is. If everything can be done with div/span/input with a name/data-name or whatever floats your boat, then the serializing route is straightforward. But once you grow out of that, you'll probably look at more custom ways, which is technically similar to your first option, with a bit more logic that just getting the .val() from the input field.
I don't really understand both of your example handling tho, but you said to not worry about the details... so :) For the form one, I assume that the .text() is just for debugging purpose? The correct code would probably first preventDefault() on the form submitting and then do a model.save($('form').serializeObject()) to both update the model and save it on the server at the same time. With some success/error call back thrown in for good measure!

Proper place for data-saving logic in AngularJS

App design question. I have a project which has a very large number of highly customized inputs. Each input is implemented as a directive (and Angular has made this an absolute joy to develop).
The inputs save their data upon blur, so there's no form to submit. That's been working great.
Each input has an attribute called "saveable" which drives another directive which is shared by all these input types. the Saveable directive uses a $resource to post data back to the API.
My question is, should this logic be in a directive at all? I initially put it there because I thought I would need the saving logic in multiple controllers, but it turns out they're really happening in the same one. Also, I read somewhere (lost the reference) that the directive is a bad place to put API logic.
Additionally, I need to introduce unit testing for this saving logic soon, and testing controllers seems much more straightforward than testing directives.
Thanks in advance; Angular's documentation may be… iffy… but the folks in the community are mega-rad.
[edit] a non-functional, simplified look at what I'm doing:
<input ng-model="question.value" some-input-type-directive saveable ng-blur="saveModel(question)">
.directive('saveable', ['savingService', function(savingService) {
return {
restrict: 'A',
link: function(scope) {
scope.saveModel = function(question) {
savingService.somethingOrOther.save(
{id: question.id, answer: question.value},
function(response, getResponseHeaders) {
// a bunch of post-processing
}
);
}
}
}
}])
No, I don't think the directive should be calling $http. I would create a service (using the factory in Angular) OR (preferably) a model. When it is in a model, I prefer to use the $resource service to define my model "classes". Then, I abstract the $http/REST code into a nice, active model.
The typical answer for this is that you should use a service for this purpose. Here's some general information about this: http://docs.angularjs.org/guide/dev_guide.services.understanding_services
Here is a plunk with code modeled after your own starting example:
Example code:
var app = angular.module('savingServiceDemo', []);
app.service('savingService', function() {
return {
somethingOrOther: {
save: function(obj, callback) {
console.log('Saved:');
console.dir(obj);
callback(obj, {});
}
}
};
});
app.directive('saveable', ['savingService', function(savingService) {
return {
restrict: 'A',
link: function(scope) {
scope.saveModel = function(question) {
savingService.somethingOrOther.save(
{
id: question.id,
answer: question.value
},
function(response, getResponseHeaders) {
// a bunch of post-processing
}
);
}
}
};
}]);
app.controller('questionController', ['$scope', function($scope) {
$scope.question = {
question: 'What kind of AngularJS object should you create to contain data access or network communication logic?',
id: 1,
value: ''
};
}]);
The relevant HTML markup:
<body ng-controller="questionController">
<h3>Question<h3>
<h4>{{question.question}}</h4>
Your answer: <input ng-model="question.value" saveable ng-blur="saveModel(question)" />
</body>
An alternative using only factory and the existing ngResource service:
However, you could also utilize factory and ngResource in a way that would let you reuse some of the common "saving logic", while still giving you the ability to provide variation for distinct types of objects / data that you wish to save or query. And, this way still results in just a single instantiation of the saver for your specific object type.
Example using MongoLab collections
I've done something like this to make it easier to use MongoLab collections.
Here's a plunk.
The gist of the idea is this snippet:
var dbUrl = "https://api.mongolab.com/api/1/databases/YOURDB/collections";
var apiKey = "YOUR API KEY";
var collections = [
"user",
"question",
"like"
];
for(var i = 0; i < collections.length; i++) {
var collectionName = collections[i];
app.factory(collectionName, ['$resource', function($resource) {
var resourceConstructor = createResource($resource, dbUrl, collectionName, apiKey);
var svc = new resourceConstructor();
// modify behavior if you want to override defaults
return svc;
}]);
}
Notes:
dbUrl and apiKey would be, of course, specific to your own MongoLab info
The array in this case is a group of distinct collections that you want individual ngResource-derived instances of
There is a createResource function defined (which you can see in the plunk and in the code below) that actually handles creating a constructor with an ngResource prototype.
If you wanted, you could modify the svc instance to vary its behavior by collection type
When you blur the input field, this will invoke the dummy consoleLog function and just write some debug info to the console for illustration purposes.
This also prints the number of times the createResource function itself was called, as a way to demonstrate that, even though there are actually two controllers, questionController and questionController2 asking for the same injections, the factories get called only 3 times in total.
Note: updateSafe is a function I like to use with MongoLab that allows you to apply a partial update, basically a PATCH. Otherwise, if you only send a few properties, the entire document will get overwritten with ONLY those properties! No good!
Full code:
HTML:
<body>
<div ng-controller="questionController">
<h3>Question<h3>
<h4>{{question.question}}</h4>
Your answer: <input ng-model="question.value" saveable ng-blur="save(question)" />
</div>
<div ng-controller="questionController2">
<h3>Question<h3>
<h4>{{question.question}}</h4>
Your answer: <input ng-model="question.value" saveable ng-blur="save(question)" />
</div>
</body>
JavaScript:
(function() {
var app = angular.module('savingServiceDemo', ['ngResource']);
var numberOfTimesCreateResourceGetsInvokedShouldStopAt3 = 0;
function createResource(resourceService, resourcePath, resourceName, apiKey) {
numberOfTimesCreateResourceGetsInvokedShouldStopAt3++;
var resource = resourceService(resourcePath + '/' + resourceName + '/:id',
{
apiKey: apiKey
},
{
update:
{
method: 'PUT'
}
}
);
resource.prototype.consoleLog = function (val, cb) {
console.log("The numberOfTimesCreateResourceGetsInvokedShouldStopAt3 counter is at: " + numberOfTimesCreateResourceGetsInvokedShouldStopAt3);
console.log('Logging:');
console.log(val);
console.log('this =');
console.log(this);
if (cb) {
cb();
}
};
resource.prototype.update = function (cb) {
return resource.update({
id: this._id.$oid
},
angular.extend({}, this, {
_id: undefined
}), cb);
};
resource.prototype.updateSafe = function (patch, cb) {
resource.get({id:this._id.$oid}, function(obj) {
for(var prop in patch) {
obj[prop] = patch[prop];
}
obj.update(cb);
});
};
resource.prototype.destroy = function (cb) {
return resource.remove({
id: this._id.$oid
}, cb);
};
return resource;
}
var dbUrl = "https://api.mongolab.com/api/1/databases/YOURDB/collections";
var apiKey = "YOUR API KEY";
var collections = [
"user",
"question",
"like"
];
for(var i = 0; i < collections.length; i++) {
var collectionName = collections[i];
app.factory(collectionName, ['$resource', function($resource) {
var resourceConstructor = createResource($resource, dbUrl, collectionName, apiKey);
var svc = new resourceConstructor();
// modify behavior if you want to override defaults
return svc;
}]);
}
app.controller('questionController', ['$scope', 'user', 'question', 'like',
function($scope, user, question, like) {
$scope.question = {
question: 'What kind of AngularJS object should you create to contain data access or network communication logic?',
id: 1,
value: ''
};
$scope.save = function(obj) {
question.consoleLog(obj, function() {
console.log('And, I got called back');
});
};
}]);
app.controller('questionController2', ['$scope', 'user', 'question', 'like',
function($scope, user, question, like) {
$scope.question = {
question: 'What is the coolest JS framework of them all?',
id: 1,
value: ''
};
$scope.save = function(obj) {
question.consoleLog(obj, function() {
console.log('You better have said AngularJS');
});
};
}]);
})();
In general, things related to the UI belong in a directive, things related to the binding of input and output (either from the user or from the server) belong in a controller, and things related to the business/application logic belong in a service (of some variety). I've found this separation leads to very clean code for my part.

Resources