ngChange

本文探讨了在AngularJS中实现文件上传功能时遇到的问题及解决方案,特别是如何正确使用自定义指令来处理文件选择事件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I've been using AngularJS for a while, noted some JQuery code really doesn't work with AngularJS.

While designing the image upload function of the editor, I used this below.

In HTML:

<input type="file" onchange="angular.element(this).scope().upload(this);" />

In Controller:

$scope.upload = function (element) {
            var fd = new FormData()
            fd.append('file', element.files[0]);
           ...http post...
}

Basically, this isn't the Angular way of calling this function. Stuck for a while then found this question on stackoverflow.

<input type="file" onchange="upload(this);" />

If the code is like this, calling function with parameter this will not pass this specific DOM element to the backend controller. Actually, this here would be the $scope of this DOM element.

If you want to access this DOM element, here you can only use $event which is an API provided by AngularJS. $event support ng-click alike event, but not ng-change.

So if this is the case,

<input type="file" ng-click="upload($event);" />

I could use below code to access this DOM element.

$scope.upload = function(e) {
    var element = angular.element(e.srcElement);
}

However, this isn't the AngularJS way.

The authentic way to do it would be writing a custom directive, and bind the directive towards event we want. Attached is Mark's solution.

<input id="searchText" ng-model="searchText" type="text" my-change>
app.directive('myChange', function() {
  return function(scope, element) {
    element.bind('change', function() {
      alert('change on ' + element);
    });
  };
});

转载于:https://my.oschina.net/shinedev/blog/522671

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值