[AngularJS] Extract predicate methods into filters for ng-if and ng-show
Leaking logic in controllers is not an option, filters are a way to refactor your code and are compatible with ng-if and ng-show.
<div ng-if="main.currentUser | user:'isAdmin'"> Admin div </div> <div ng-if="main.currentUser | user:'isntAdmin'"> Standard user div </div>
var app = angular.module('App', []); app.controller('MainCtrl', function() { var currentUser = { rights: [] }; function setAdmin(){ resetAdmin(); currentUser.rights.push('admin'); } function resetAdmin(){ currentUser.rights = []; } this.currentUser = currentUser; this.setAdmin = setAdmin; this.resetAdmin = resetAdmin; }); app.filter('user', function(){ var rules = { isAdmin: function(user){ return user.rights.indexOf('admin') !== -1; }, isntAdmin: function(user){ return !rules.isAdmin(user); } }; return function(user, rule){ return rules[rule](user); }; });