简体   繁体   English

Angular.js ng-show只是不起作用

[英]Angular.js ng-show just doesn't work

I have a problem with Angular's ng-show and I was looking for the answer everywhere and nothing seems to be working. 我对Angular的ng-show有一个问题,我到处寻找答案,似乎没有任何工作。 I need form to be showing when button is clicked but it doesn't. 我需要在单击按钮时显示表单,但事实并非如此。 Button is calling function that has console.log in it and it works but show is not changing its state, here's code: Button正在调用其中包含console.log函数,它可以工作,但show不会改变它的状态,这里是代码:

<div class="row" ng-controller="MyCtrl">
   <form ng-show="show">
     <input type="text" ng-model="name" placeholder="Name" required>
   </form>
   <a href="#"class="button large" ng-click="showAddForm()">Show Me!</a>
</div>

In app.js: 在app.js中:

.controller('MyCtrl', ['$scope',function($scope) {
    $scope.showAddForm = function(){
        console.log("click click");
        $scope.show = true;
    }; 
}]);

I assume you want the form to be hidden at the beginning and when you click the 'Show Me' button to appear. 我假设您希望在开头隐藏表单,并在单击“显示”按钮时显示。

If this is the case, your code was 99% there. 如果是这种情况,那么你的代码就是99%。 All you need to do is to initialize $scope.show to false at the start of the controller code. 您需要做的就是在控制器代码的开头将$scope.show初始化$scope.show false

app.controller('MyCtrl', ['$scope',function($scope) {

    $scope.show = false;

    $scope.showAddForm = function(){
        console.log("click click");
        $scope.show = true;
    }; 
}]);

Refer plunk https://plnkr.co/edit/fwVEkEQzztKgOYkLUOsK?p=preview for a full working version. 请参阅插件https://plnkr.co/edit/fwVEkEQzztKgOYkLUOsK?p=preview以获取完整的工作版本。

Edit : While I was answering your question @Sunil D has already answered with a very good explanation of why its behaving the way its behaving 编辑:当我回答你的问题时@Sunil D已经回答了一个非常好的解释,说明为什么它的行为表现方式

Hope this helps 希望这可以帮助

Remember you can use a Stackoverflow code snippet in your questions & answers. 请记住,您可以在问题和答案中使用Stackoverflow代码段。 Your code works if you add the "app" part in html & js: 如果你在html&js中添加“app”部分,你的代码就可以了:

 angular .module("app",[]) .controller('MyCtrl', ['$scope',function($scope) { $scope.showAddForm = function(){ console.log("click click"); $scope.show = !$scope.show; }; }]); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="app" class="row" ng-controller="MyCtrl"> <form ng-show="show"> <input type="text" ng-model="name" placeholder="Name" required> </form> <a href="#"class="button large" ng-click="showAddForm()">Show/Hide</a> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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