I'm writing a Single Page App with the help of Angular. My previous experience is just kludged together JavaScript with no strict testing or adherence to models.
I've written a small test app (imagine something much like the yeoman todo app : http://yeoman.io/codelab.html). In said app, if the user tries adding a duplicate entry, I'd like to throw an error.
So on the html file I've got an add button:
<button ng-click="addPerson(newPerson)">Add</button>
This runs the addPerson function in the controller:
$scope.addPerson = function (name) {
try {
$scope.awesomePeople = PeopleListService.addPerson(name);
}
catch(err) {
// do something with err
}
};
Which in turn runs the appropriate function in the service/factory (which in the future will get it's data from a DB -- this is just a learning process for me):
fact.getPeople = function () {
return peopleList;
};
fact.addPerson = function(name) {
if (peopleList.indexOf(name)===-1) {
peopleList.push(name);
return fact.getPeople();
} else {
throw 'Name (' + name + ') already in awesomePeople list';
}
};
This all works fine and dandy. (these are just snippets)
I've been taught to throw errors and to catch and handle them gracefully. In this case, I'd like to notify the user that they tried to add a duplicate.
My question is slightly philosophical -- if I display anything in the controller (say, alert(err);
, I've violated the MVC
model by having the controller directly contact the user - no? This will have coupled the controller to the view/UI - again, something I don't want to do. Is it best to simply re-throw the error from the controller and then catch it in the html/view? If so - is there a good way to do that within an angular expression?
Thoughts?
I have looked deeper, using one of the answers below, and found the following link informational: UI Notifications with angular js and might give this angular notifications plugin a try: https://github.com/Swimlane/angular-notifications