来自控制器中多个ng-show功能的单一功能

时间:2016-01-20 23:28:58

标签: javascript angularjs

我在Angular中编写了一些函数,通过作用域在页面上显示多个ng-show属性。我尝试使用if else语句将所有三个函数放入单个函数中,但是我无法再次触发函数。我想知道是否有办法在单个函数中执行此操作,以及此类功能的最佳实践是什么。

JS小提琴在这里 - http://jsfiddle.net/ezy_/01L050mr/2/

这是目前分布在3个不同功能中的JS。

let sql = "select * from TASKS where TASK_START_TSTAMP >= \(startDate.timeIntervalSince1970) and TASK_START_TSTAMP < \(endDate.timeIntervalSince1970)"

如果我将函数设置为从单个statesTrigger(resp)函数触发,是否需要$ watch或$ apply函数来触发更新?

2 个答案:

答案 0 :(得分:2)

看看这里:updated with 1 function

&#13;
&#13;
  $scope.triggerState = function (state) {
    if (state == 'skills') {
      $scope.skillsStateTrigger();
    } else if (state == 'roles') {
      $scope.rolesStateTrigger();
    } else if (state == 'quals') {
      $scope.qualsStateTrigger();
    }
  }
&#13;
  <button ng-click="triggerState('skills')">Skills</button>
  <button ng-click="triggerState('roles')">Roles</button>
  <button ng-click="triggerState('quals')">Quals</button>
&#13;
&#13;
&#13;

您甚至可以在HTML中更加具体,如下所示:State variable

&#13;
&#13;
<body ng-app="app" class="ng-scope">
  <div class="container ng-scope" ng-controller="AppCtrl">
    <button ng-click="currentState = 'skills'">Skills</button>
    <button ng-click="currentState = 'roles'">Roles</button>
    <button ng-click="currentState = 'quals'">Quals</button>
    <div class="row" ng-show="currentState == 'skills'" style="display: none;">
      Skills State Active
    </div>
    <div class="row" ng-show="currentState == 'roles'" style="display: none;">
      Roles State Active
    </div>
    <div class="row" ng-show="currentState == 'quals'" style="display: none;">
      Quals State Active
    </div>
  </div>
</body>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

这是你的重构。诀窍是使用一个对象来存储3个状态。

JS:

let mOptions = [NSMigratePersistentStoresAutomaticallyOption: true,
    NSInferMappingModelAutomaticallyOption: true]

html:

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

function AppCtrl($scope) {
    $scope.states = {
     skills: false,
     roles: false,
     quals: false
  };

  $scope.trigger_state = function(state) {
    for(var i in $scope.states) {
      $scope.states[i] = (i == state);
    }
  };
}

在这种情况下,使用3个状态是个坏主意,你可以使用1个变量来存储&#34;状态&#34; =&#34; mystate&#34;例如(因为州是独家的)。