文本更改后添加新按钮

时间:2017-03-21 12:52:01

标签: html angularjs

我在网上使用Angualr。 我在html代码中有这个部分:

 <div class="form-group">
              <div class="text-form" style="float: left;">Companion URL</div>
              <input type="text" placeholder="Companion URL" class="companion-url-box" ng-model="newCreative.companionUrl">
            </div>

我想添加方法(在Controller中),当文本改变时,它会添加一个新按钮。 我该怎么做?我无法理解ng-change的工作原理。

感谢

2 个答案:

答案 0 :(得分:0)

只需使用ng-if检查范围内是否存在newCreative.companionUrl

<div class="form-group">
  <div class="text-form" style="float: left;">Companion URL</div>
  <input type="text" placeholder="Companion URL" class="companion-url-box" ng-model="newCreative.companionUrl">
  <input type="button" value="Click me" ng-if="newCreative.companionUrl">
</div>

您还可以使用函数来验证按钮可见性:

<强>的index.html

<!doctype html>

<html lang="en" ng-app="app">
<head>
  <meta charset="utf-8">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
  <script src="scripts.js"></script>
</head>

<body ng-controller="SampleController as ctrl">

    <div class="form-group">
      <div class="text-form" style="float: left;">Companion URL</div>
      <input type="text" placeholder="Companion URL" class="companion-url-box" ng-model="newCreative.companionUrl">
      <input type="button" value="Click me" ng-if="ctrl.isButtonAvailable()">
    </div>

</body>
</html>

<强>的script.js

angular.module('app', []);

angular.module('app').controller('SampleController', function ($scope) {
    var ctrl = this;

    ctrl.isButtonAvailable = function() {
        if(!$scope.newCreative) {
            return false;
        }
        // Ensure companion url starts with https:// using a regular expression
        return /^https:\/\//.test($scope.newCreative.companionUrl);
    }
}); 

工作示例

查看此Plunker:https://plnkr.co/edit/n8VtJrenePGf9hCbmzWJ

答案 1 :(得分:0)

您可以在输入和ng-if或ng-show按钮上使用指令ng-change,在控制器上使用一些代码。

检查一下:

http://codepen.io/mQuixaba/pen/oZqXWG?editors=1111

HTML:

<div ng-app="myApp" ng-controller="MyController">
  <label for="input">Text:</label>
  <input type="text" id="input" ng-model="text" ng-change="showButton=true"/>
  <button ng-if="showButton" ng-click="hideButton()">My Button</button>
</div>

JS:

angular
  .module('myApp', [])
    .controller('MyController', function($scope){
      $scope.showButton = false;
      $scope.text = "My text";

      $scope.hideButton = function() {
        $scope.showButton = false;
      }
    });