AngularJs: How to check for changes in file input fields?

前端 未结 15 1155
傲寒
傲寒 2020-11-22 09:06

I am new to angular. I am trying to read the uploaded file path from HTML \'file\' field whenever a \'change\' happens on this field. If i use \'onChange\' it works but when

15条回答
  •  清酒与你
    2020-11-22 09:51

    Angular elements (such as the root element of a directive) are jQuery [Lite] objects. This means we can register the event listener like so:

    link($scope, $el) {
        const fileInputSelector = '.my-file-input'
    
        function setFile() {
            // access file via $el.find(fileInputSelector).get(0).files[0]
        }
    
        $el.on('change', fileInputSelector, setFile)
    }
    

    This is jQuery event delegation. Here, the listener is attached to the root element of the directive. When the event is triggered, it will bubble up to the registered element and jQuery will determine if the event originated on an inner element matching the defined selector. If it does, the handler will fire.

    Benefits of this method are:

    • the handler is bound to the $element which will be automatically cleaned up when the directive scope is destroyed.
    • no code in the template
    • will work even if the target delegate (input) has not yet been rendered when you register the event handler (such as when using ng-if or ng-switch)

    http://api.jquery.com/on/

提交回复
热议问题