【问题标题】:How to handle the below jQuery in Angular method如何在 Angular 方法中处理下面的 jQuery
【发布时间】:2016-04-12 18:09:39
【问题描述】:

下面的简单 jQuery 不会在我的 Angular Web 应用程序中运行。它在控制台中运行,但在作为外部文件包含时不会被读取。同一文件中的其他脚本运行,但这没有。有什么想法吗?我如何使用正确的 Angular 方式重写以下内容(我目前是 Angular 的新手)。

$("#button").on("click", function() {
   $('input.ng-pristine').show(); //class selector for the div to show
});

【问题讨论】:

  • 你的代码准备好了吗?
  • 为什么要在 Angular 应用程序中这样做?为什么不使用 ng-click 指令?
  • 为什么不用角度逻辑来处理呢?
  • “如何在 Angular 之外使用 jQuery” 不要。
  • 我不同意,但各有各的意见。

标签: javascript jquery angularjs


【解决方案1】:

在 Angular 中如何做到这一点的总体思路是这样的

//your button
<button id="button" ng-click="clickButton()">your button </button>
//your input to hide
<input ng-show="!hideInput" />

在控制器中

 $scope.clickButton = function() {
      $scope.hideInput = !$scope.hideInput;
 };

现在,我不知道您是否有用于显示和隐藏它的特殊用例,但此按钮将按原样切换显示/隐藏。如果您要打开和关闭它,您可以像这样进一步简化它:

 <button id="button" ng-click="hideInput = !hideInput">your button </button>

如果您不希望它切换,这可能对您不起作用,但想法是 $scope.hideInput 是一个布尔值,用于控制输入上的 ng-show 或 ng-hide。

【讨论】:

    【解决方案2】:

    你应该使用角度指令

    <input type="button" value="Click me" ng-click="myFunction()">
    
    
    // In your angular controller
    $scope.myFunction = function() {
       // do something
    };
    

    【讨论】:

      【解决方案3】:

      正确的方法是使用angular指令的

      编辑:

      angular ng-clickng-show 将完成这项工作:

      代码示例:

      在 html 文件中:

      <body ng-app="example.module">
         <div ng-controller="myCtrl">
             <button id='button' ng-click="show()"> show it! </button>
            <input class="pristine" ng-show="visible">
         </div>
      </body>
      

      在js文件中:

      angular.module('example.module')
         .controller('myCtrl', function($scope){
      
           $scope.visible = false;
      
           $scope.show = function(){
              $scope.visible = true;
            }
      
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-01
        • 2021-07-14
        • 2014-11-18
        • 2019-04-11
        相关资源
        最近更新 更多