几个菜单,隐藏和隐藏功能,代码审查AngularJS,CSS,JS

时间:2017-10-24 16:56:28

标签: javascript css angularjs

我做了显示和隐藏菜单的功能,但我认为它可以保存得更短。

有人可以进行代码审查并告诉我如何使其成为更好的代码,哪些更好用?请。

你可以通过关闭菜单而不是向身体添加动作来做到这一点

控制器:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function ($scope) {
    $scope.name = '';
    $scope.toggle = false;

    $scope.activeMenu = function (name, toggle) {
        $scope.name = name;
        $scope.toggle = toggle;
        console.log(name, toggle);
    }
});

模板:

<body ng-app="plunker" ng-click="name = ''; toggle = false;" ng-controller="MainCtrl">

    <div class="account-item">
        <div class="account-heading">
            <h4 class="account-title">
                <a href="#/Messages" ng-click="activeMenu('Home', !toggle);$event.stopPropagation() "> Home </a>
            </h4>
            <div class="menu" ng-click="activeMenu('Home', true);$event.stopPropagation() " ng-class="{active : name === 'Home' && toggle === true}">
                <ul>
                    <a href="#" ng-click="activeMenu('Home', false);$event.stopPropagation() ">close</a>
                    <li>Home</li>
                </ul>
            </div>
        </div>
    </div>

    <div class="account-item">
        <div class="account-heading">
            <h4 class="account-title">
                <a href="#/Messages" ng-click="activeMenu('Contact', !toggle);$event.stopPropagation() "> Contact </a>
            </h4>
            <div class="menu" ng-click="activeMenu('Contact', true);$event.stopPropagation() " ng-class="{active : name === 'Contact' && toggle === true}">
                <ul>
                    <a href="#" ng-click="activeMenu('Contact', false);$event.stopPropagation(); toggle=false; ">close</a>
                    <li>Contact</li>
                </ul>
            </div>
        </div>
    </div>


    {{name}} {{toggle}}
</body>

样本

https://codepen.io/Turqus/pen/jGjyyw

1 个答案:

答案 0 :(得分:0)

这应该给你一个想法和一个更好的方法

(function(app) {
  app.controller('Ctrl', function() {
    this.tab = 1;

    this.setTab = function(tabId) {
      this.tab = tabId;
    };

    this.isSet = function(tabId) {
      return this.tab === tabId;
    };
  });
})(angular.module('App', []));
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>

<div class="container" ng-app="App" ng-controller="Ctrl as vm">
  <ul class="nav nav-pills">
    <li ng-class="{ active: vm.isSet(1) }">
      <a href ng-click="vm.setTab(1)">Home</a>
    </li>
    <li ng-class="{ active: vm.isSet(2) }">
      <a href ng-click="vm.setTab(2)">Contact</a>
    </li>
  </ul>

  <div ng-show="vm.isSet(1)">
    <h4>Home</h4>
  </div>
  <div ng-show="vm.isSet(2)">
    <h4>Contact</h4>
  </div>
</div>