简体   繁体   中英

How to use ng-if in angularJS

I have used angularJS and i wonder how to use its if statement like this way. I don't know if my question is right but i just want to explain it through my example.

I have if like this..

<div data-ng-if="book.Availability>0">
  <div class="col-xs-12 col-md-12 nopadding" style="border-right:solid 6px blue">
     //some html div's here with angularJS
  </div>
</div>

<div data-ng-if="book.Availability==0">
  <div class="col-xs-12 col-md-12 nopadding" style="border-right:solid 6px red">
     //some html div's here with angularJS
  </div>
</div>

I have a code like that.. that //some html div's here with angularJS have common codes the only thing that deferent is the red and blue color in the container..

I think it is redundant to use that kind of code.. is it possible to use same that //some html div's here with angularJS for both if?

I tried like this.

<div data-ng-if="book.Availability>0">
      <div class="col-xs-12 col-md-12 nopadding" style="border-right:solid 6px blue">
  </div>
  <div data-ng-if="book.Availability==0">
      <div class="col-xs-12 col-md-12 nopadding" style="border-right:solid 6px red">
  </div>
    `//some html div's here with angularJS`

but there's no output..

Thanks for help..

I know my question is different from what i want.. but i don't really have an idea how to ask it..

ng-if is not the approach you should leverage to solve that problem. You are uneccesarilly duplicating DOM when all you have is a styling issue. Use your condition statement to apply a class to the div container rather than duplicating.

http://plnkr.co/edit/mU0P7Bp1mFidWWfIUyX2?p=preview

<head>
<script data-require="angular.js@*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
<style>
  .book{border:solid 1px blue;}
  .unavailable{border-color: red;}
</style>
</head>

<body>
<h1>Hello Plunker!</h1>
<div ng-class="{'unavailable' : true}" class="book">
        Moby Dick
  </div>

  <script>
    var app=angular.module("app",[]);
    angular.bootstrap(document,["app"]);
  </script>
</body>

</html>

I am not 100% sure what is your requirement. but looks like you want to display different contents according to a condition.

I have used your html and create a sample. please check whether what you want is this.Controller look like below code. TO check full sample go to the link.

function MyCtrl($scope) {
$scope.book={Availability:12};

}

Sample Code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM