繁体   English   中英

在ng-repeat中调用函数

[英]Calling a function in ng-repeat

我在ng-repeat中有一个<input type="file"> ,我希望每当ng-repeat中<input type="file">元素的元素值发生变化时调用一个函数。

我尝试调用$(#"id").change()函数,但它不起作用。 我尝试过使用ng-change,但是当我使用ng-change时,ng-repeat不起作用。 这是我的代码:

在HTML中

<div ng-repeat="item in items">
    <input  type="file" accept="image/*" id="add_{{$index}}"/>
</div>

在JS

$("#add_images").change(function() {
    alert("HI");
}

为什么要混合使用Angular和JQuery?

您拥有Angular中的所有内容,您可以轻松使用它!

在HTML中

<div ng-repeat="item in items">
    <input  type="file" accept="image/*" id="add_images" ng-change="doSomething()"/>
</div>

在控制器JS中

$scope.doSomething = function(){
  //do whatever you want to
}

Angular不支持输入类型=文件github的 ng-change

但有一些方法可以在范围内触发方法,请参阅我的jsfiddle

<div>
  <div ng-controller='MyCtrl'>
    <pre>{{items | json }}</pre>
    <div ng-repeat="item in items">
      <input type="file" onchange='angular.element(this).scope().onchange(this)' />
    </div>
  </div>
</div>
angular.module('myApp', [])
  .controller('MyCtrl', function($scope) {
    $scope.items = ['test', 'test2'];
    $scope.onchange = function(that) {
      alert(that.value)
    }
  });

首先要在ng-repeat中重复id。 Id应该是唯一的。 我建议你使用。

<div ng-repeat="item in items">
  <input  type="file" accept="image/*" />
</div>

$ index是item的索引。

第二次使用Javascript的onchange功能

<div ng-repeat="item in items">
  <input  type="file" accept="image/*" onchange="angular.element(this).scope().myFunc()" id="add_images_$index"/>
</div>

将功能附加到范围

$scope.myFunc = function() {
  alert("Hi");
}

如果您尝试捕获输入类型文件元素的ng-change,也请参考<input type =“file”上的 ng-change。

<div>
  <div ng-app="myApp" ng-controller='MyCtrl'>    
    <div ng-repeat="item in items">
      <input type="file" ng-change="functionName()" />
    </div>
  </div>
</div>

var app = angular.module('myApp', []);
app.controller('MyCtrl', function($scope) {
     $scope.functionName= function() {
     alert("hi your call worked successfully");
     }; 
});

你可以使用更好更清洁的指令。

HTML:

<div ng-repeat="item in items">
    <input  type="file" accept="image/*" id="add_{{$index}}" dir-change/>
</div>

JS:

directive('dirChange',function(){

  return {
    link : function(scope,ele){ 

      ele.bind('change',function(){ 
          //code

      });
    }
  }

})

这是Plunker

暂无
暂无

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

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