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

試著忘記壹切 提交于 2020-01-11 13:22:07

问题


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);
    }

}

回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/27342106/why-is-my-ng-if-not-working-its-not-hiding-the-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!