zoukankan      html  css  js  c++  java
  • [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);
      };
    });
  • 相关阅读:
    easyui好例子,值得借鉴
    DDL 和DML 区别
    兼容IE的文字提示
    搭代理
    美国服务器
    跟随滚动条滚动
    JS Array对象
    JS 内置对象 String对象
    JS 对象
    JS 二维数组
  • 原文地址:https://www.cnblogs.com/Answer1215/p/4599080.html
Copyright © 2011-2022 走看看