dimanche 30 novembre 2014

AngularJs, reducing logic in html templates


I have an html template where the conditionals in the ng-ifs and ng-shows are getting a bit too complex to belong in the UI. For example, this is to determine if payment controls should be displayed:



<div ng-show="ticket.status == 0 &&
((ticket.orgTicketId === '' && ticketControl.balance > 0 ) ||
(ticket.orgTicketId !== '' && ticketControl.balance < 0))">


I would like to simplify this to something like this:



<div ng-show="ticket.paymentsAllowed">


I would prefer to not move the logic into the controller, since I am trying to keep it as clean as possible as well.


In C#, which is where I come from, I would just add a property to the Ticket class called PaymentsAllowed and move the logic there.


I am fairly new to Javascript and AngularJs and I am looking for advice on how to accomplish something similar here, so that I can clean up the html templates and make them more legible.


The Angular app gets JSON from a WebAPI backend, which I simply assign to the $scope; this is all working well. Here is a simplified example of retrieving a ticket.


The ticketService reads the ticket view model from the backend:



function getTicket(ticketId) {
var deferred = common.$q.defer();

common.$http.get("api/tickets/" + ticketId)
.success(function (ticket) {
deferred.resolve(ticket);
}));

return deferred.promise;
}


The controller uses the ticketService to retrieve ticket and assign to $scope.ticket:



ticketService.getTicket(123).then(
function (ticket) {
$scope.ticket = ticket;
});


I like the simplicity of just retrieving view models in the form of JSON data from the WebAPI and binding it straight to the proper scope, but what is a simple, clean way to add some simple business logic to these javascript objects?





Aucun commentaire:

Enregistrer un commentaire