ngChange

原创
2015/10/27 15:23
阅读数 128

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);
    });
  };
});
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部