This afternoon I’ve been playing a little with AngularJS, and finally I’ve fully understood how the service $parse works.

I was trying to create a directive that makes use of HTML5’s file reading API. I dind’t want to create a new element because the input type="file" element is okay. So I’ve created an onReadFile attribute which gets a function as a parameter. This function performs some logic with the file content. In this example I will only show that content on screen.
AngularJS HTML5 file APIThis directive works very like others like ngClick or ngSubmit. But the main difference is our directive is receiving the file content instead an event.

Our example’s HTML code will be so short. In consists of an input type="file" element. When the content of the file has been read, the showContent method of the controller shall be called.

<div class="container">
<h1>Select file</h1>
<input type="file" on-read-file="showContent($fileContent)" />
<div>
<h2>File content is:</h2>
<pre>{{ content }}</pre>
</div>
</div>

This showContent function only gets the file content as a parameter, and sends it to the view.

$scope.showContent = function($fileContent){
$scope.content = $fileContent;
};

Now the directive. As you will see, its code isn’t so large. Its restrict value is A, because as I said it’s going to be an attribute. It also does not need an isolated scope. Respecting the File API, I’m not going to tell so much than I’ve already said. Also there are many people that make better explanations than me.

Let’s take a look at our directive:

/*
* Copyright (c) 2015 Alejandro Such Berenguer
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:

* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.

* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

myapp.directive('onReadFile', function ($parse) {
  return {
    restrict: 'A',
    scope: false,
    link: function(scope, element, attrs) {
      var fn = $parse(attrs.onReadFile);

      element.on('change', function(onChangeEvent) {
        var reader = new FileReader();

        reader.onload = function(onLoadEvent) {
          scope.$apply(function() {
            fn(scope, {$fileContent:onLoadEvent.target.result});
          });
        };

        reader.readAsText((onChangeEvent.srcElement || onChangeEvent.target).files[0]);
      });
    }
  };
});

On the directive, we use the attrs.onReadFile attribute to identify the function to be called (showContent($fileContent) in the example). Then we pass it to the $parse service. This service converts an expression into a function. When it’s called, that function needs two arguments:

  1. A context. In our case will be the scope. With this, we are saying: call the showContent($fileContent) function of the scope.
  2. A JSON object which content will replace the variables that has the same name on the context. This way we will be able to override the values of the function arguments.

This directive could be so useful in applications where we want to perform a data load, whatever the reason is: a CSV client data, load a saved game, etc.

You can see a fully working example in this fiddle.

Anuncios