简体   繁体   中英

ng-controller does not output correctly

I try to run the following trivial HTML:

  <!DOCTYPE html>
  <html ng-app="tempApp">
<head>
    <script src="js_libs/angular/angular.min.js"></script>
    <script src="js_libs/angular/bootstrap.js"></script>
    <script src="controller.js"></script>
    <link rel="stylesheet" href="css/bootstrap.css">
</head>
<body ng-controller="TempCtrl">
    <div class="container">
        <h2>Enter temperature :</h2><input type="number" ng-model="temp">
        <p ng-show="temp < 17">{{temp}} is too short !</p>
        <p ng-show="temp = 17">{{temp}} is OK !</p>
        <p ng-show="temp > 17">{{temp}} is too high !</p>
    </div>
</body>

File controller.js is:

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

 app.controller("TempCtrl", function ($scope){
     $scope.temp = 17;
 });

The problems are:

  1. The output shows the input box with 17 default and the message 17 is ok . I can not change the value in the input box, neither by clicking on the arrows nor by entering direct data.
  2. At the same time, trying to apply tags such as < h1 > to < p > has no effect. I tried for example:

      <p ng-show="temp < 17"><h1>{{temp}} is too short !</h1></p> 

What is the solution for these problems ? Thanx.

You have the value 17 assigned in your ng-show. Comparing the value should be via == or ===. That should solve majority of your problem.

<p ng-show="temp === 17">{{temp}} is OK !</p>

regarding the first problem:

use temp == 17 or temp === 17 for comparison, instead of temp = 17 , which assigns 17 to temp and hence you cannot change the value anymore.

regarding h1 inside p :

It is invalid HTML, and so when the browser encounters h1 inside p , it closes the p tag, then starts a new h1 tag, so in your case, if you write

<p ng-show="temp < 17">
    <h1> too short </h1>
</p>

then the browser would render it as

<p ng-show="temp < 17"></p>
<h1> too short </h1>
<p></p>

PS: can't say about all browsers, but chrome and probably firefox have this behavior.

You're using assigning operator instead of comparing operator

Solution :

<p ng-show="temp = 17">{{temp}} is OK !</p>

change to =>

<p ng-show="temp === 17">{{temp}} is OK !</p>

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