search

Home  >  Q&A  >  body text

angular.js - angularjs中怎么动态的插入删除元素

就像这样,我想按下回车之后在html中添加一个元素<p class='main'></p>, if下面该怎么写?还有一个问题,angularjs到底是怎么来操作DOM的,刚开始学,不太理解。
var app = angular.module('myApp',[])

.controller('todoCtrl',function ($scope) {

    $scope.enterEvent = function(e) {
        var keycode = window.event?e.keyCode:e.which;
        if(keycode==13){

        }
    }
});
黄舟黄舟2744 days ago611

reply all(2)I'll reply

  • 滿天的星座

    滿天的星座2017-05-15 17:12:00

    Data-driven model.
    You need to change your thinking about operating dom.
    What do you want to do after entering? You need an extra dom. Assuming that the previous dom number is 0, then if you press Enter, it will be +1.
    Then it’s easy. You first define a variable. Whether the variable is initialized to 1 or 10,000 depends on your mood.

    <!DOCTYPE html>
    <html>
    
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width">
        <title>JS Bin</title>
        <script src="//cdn.bootcss.com/angular.js/1.5.8/angular.min.js"></script>
    </head>
    
    <body ng-app="myApp">
        <p id="father" ng-controller="todoCtrl">
    
            <p>
                <input id="txt" type="text" ng-keyup="enterEvent($event)" value="">
            </p>
            <p ng-repeat="(i,item) in myDom" class='main'>我是第{{i+1}}个main {{myDom}}</p>
        </p>
    </body>
    <script>
        var app = angular.module('myApp', []);
    
        app.controller('todoCtrl', function($scope) {
            $scope.myDom = [];
            var i = 1;
            $scope.enterEvent = function(e) {
                var keycode = window.event ? e.keyCode : e.which;
                if (keycode == 13) {
                    $scope.myDom.push(i)
                    i++;
                }
            }
    
        });
    </script>
    
    </html>

    reply
    0
  • 某草草

    某草草2017-05-15 17:12:00

    You can put this <p class='main'></p>先写在页面上,写在todoCtrl in. Then add the ngShow syntax to the element to control the hiding and display of the element at any time:

    <p class='main' ng-show="showMain"></p>
    $scope.showMain=false;
    
    $scope.enterEvent = function(e) {
        var keycode = window.event?e.keyCode:e.which;
        if(keycode==13){
            $scope.showMain=true;
        }
    }

    reply
    0
  • Cancelreply