如何在angularjs的选项中使用ng-if?

时间:2018-03-15 07:57:25

标签: angularjs angularjs-directive angularjs-scope

如果on,我想将状态更改为status == 1,如果off,则要更改为status == 0。我能够以这种方式在桌面上做到这一点

<td>
    <span ng-if="configuration.rule.onSuccess == 1">
        On
    </span>
    <span ng-if="configuration.rule.onSuccess == 0">
       Off
    </span>
</td>

如何在选择框选项中实现相同的功能

<td>
  <select class="browser-default event relay state" required>
     <option ng-value="n.onSuccess">{{configuration.rule.onSuccess}}</option> 
     <option value="1">On</option>
     <option value="0">Off</option>
  </select>

我需要打开和关闭<option ng-value="n.onSuccess">{{configuration.rule.onSuccess}}</option>而不是显示0和1.如果我使用ng-if,它会显示打开和关闭。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

添加ng-model以选择标签。由于您希望将选项值绑定到onSuccess变量。

这是工作代码。更改了一些范围变量以显示示例演示

<!DOCTYPE html>
<html>

<head>
  <script data-require="jquery@3.0.0" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
  <link data-require="bootstrap@3.3.7" data-semver="3.3.7" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
  <script data-require="angular.js@1.6.6" data-semver="1.6.6" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.17/angular-filter.min.js"></script>
  <script src="https://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.6.0.js" type="text/javascript"></script>
  <script>
    (function() {

      var app = angular.module("testApp", ['ui.bootstrap', 'angular.filter']);
      app.controller('testCtrl', ['$scope', '$http', function($scope, $http) {
      }]);

    }());
  </script>
  <style></style>
</head>

<body ng-app="testApp">
  <div ng-controller="testCtrl">
    
    <div>
      <span ng-if="onSuccess == 1">
          On
      </span>
      <span ng-if="onSuccess == 0">
         Off
      </span>
    </div>
    
    <select class="browser-default event relay state" required ng-model="onSuccess">
       <option ng-model="onSuccess">{{configuration.rule.onSuccess}}</option> 
       <option value="1">ON</option>
       <option value="0">OFF</option>
    </select>
    
  </div>
</body>

</html>

答案 1 :(得分:-1)

一种方法:

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

myApp.controller('indexController', function($scope){
  $scope.configuration = {
    "role": {
       "onSuccess": 0
    }  
  };  
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="indexController">
  <select ng-model="configuration.role.onSuccess">
    <option value="1">On</option>
    <option value="0">Off</option>
  </select>
  <input type="button" value="Set Value to ON" ng-click="configuration.role.onSuccess=1;">
  <input type="button" value="Set Value to OFF" ng-click="configuration.role.onSuccess=0;">
</body>