Why is my ng-if not working? It's not hiding t

2019-03-04 10:32发布

In my Angular app, I want a certain div to appear if a variable is true, and to disappear if it is false.

However, it is not working. See my Fiddle

Can anyone help me understand why?

HTML

<div ng-controller="MyCtrl">
    <div id="newProjectButton" class="project" ng-click="newProjectActive()" ng-if="!creatingNew">
            <h1> + </h1>
            <h3> New Project </h3>
    </div>
    <div id="newProjectActive" class="project" ng-if="creatingNew">
        <form>
            <input name="name" ng-model="newProjectName" type="text"></input>
            <button ng-click="newProject()" type="submit" class='btn btn-primary'>Save</button>
        </form>
    </div>
</div>

JS

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

function MyCtrl($scope) {
    $scope.name = 'Superhero';

    $scope.creatingNew = false;

    $scope.newProjectActive = function () {
        $scope.creatingNew = true;
    }

    $scope.newProject = function () {
        alert($scope.newProjectName);
    }

}

2条回答
霸刀☆藐视天下
2楼-- · 2019-03-04 11:03

your angular version is 1.0.1. directive ng-if is not in this version of angular. its introduce in angular 1.1.5 check this article and check it in angular under Directives topic change log

AngularJS first added the ngIf directive in 1.1.5

please update the angular version

here is the Demo

your controller should be like

myApp.controller("MyCtrl" , function($scope) {

because the global controllers are not supported by default in angular 1.3... check this one

查看更多
3楼-- · 2019-03-04 11:25

First, when I looked at your fiddle, there was older version of your example there,

Second, which actually may be a reason, is in that example you were using angular in version 1.0.1, and i believe that version didn't implement ng-if. Updating to latest version will fix your problem

查看更多
登录 后发表回答