JSX preprocessor – A syntax sugar for ReactJS

The JSX preprocessor

JSX preprocessor it is a step that adds XML syntax to JavaScript. You can definitely use React without JSX but JSX makes React a lot more elegant.

When you start typing code, driving yourself into the amazing world of web programming sometimes you may feel overwhelmed when you have to select a tool, a library or a framework as your initial learning point. Out there are too many tools, each one with different features aiming the same goal in their own way. Eventually you realize that HTML and CSS are not enough, you need JavaScript. And now for react you are able to use
JSX preprocessor.

JSX preprocessor

At some point, vanilla JavaScript became too heavy and hard in order to achieve certain task, the most efficient way is to make use of a library or a framework.
This time is the turn for ReactJS, it is a JavaScript library, and specifically one of its many features: JSX. Now, we will assume you already know something about ReactJs and the ecosystem around it. Otherwise you should start here first and then move on to this topic.

ReactJS feature:
Basically JSX is an inline markup that looks like XML/HTML and gets transformed to JavaScript (sometimes it can remind you a template language). It is possible to use ReactJS without JSX but JSX makes ReactJS code more elegant. A JSX expression starts with an XML/HTML-like open tag, and ends with the corresponding closing tag, it also supports the XML syntax so you can optionally leave the closing tag off. See the follow example:

 
const hw = <p>Hello, world!</p>;

This code is just JSX syntax example but you also can do things like embed JavaScript expressions in JSX by wrapping it in curly braces:

 

function hello(text) {
  return text.firstWord + ' ' + text.secondWord + '!';
}

const text = {
  firstWord: 'Hello',
  secondWord: 'World'
};

const element = (
  <p>
    This is a, {hello(text)}!     // embed JavaScript expression 
  </p>
);

Even specify attributes like follow:
You may use quotes to specify string literals as attributes:

 
const element = <div z-index="1"></div>;

You may also use curly braces to embed a JavaScript expression in an attribute:

 

var style = { backgroundImage: 'url(picture.png)', height: 10, width: 15 };
return <div style={style}></div>;

Now let’s analyze an example combined with ReactJS.

ReactJS applying JSX

 
var test = (  
  <div className='test-example'>//notice the parameter className instead of class
    <img 
      src='image.png'
      className='test-example'
    />
  </div>)

ReactDOM.render(test, document.getElementById('myapp'))

As you can see, it is like write HTML/XML code inside JavaScript but at the end it is just JavaScript. The special consideration is that JSX makes you name the attributes in a different way form the standard, in the example above, the ‘class’ for CSS must be named ‘className’ instead of the html standard attribute ‘class’.

Basically JSX produces React “elements” and according to the official documentation ‘JSX just provides syntactic sugar to React.createElement(…) function’, see below:

 

<MyButton color="green" shadowSize={10} >
  Go!
</MyButton>


 
compiles into:
React.createElement(
  MyButton,
  {color: 'green', shadowSize: 10},
  'Go!'
)

JSX preprocessor Pros:

Declarative syntax:
Provides a very easy way to import static HTML or migrate from JavaScript templates. Plus, its enforces good syntactical restrictions similar to XHTML that improves quality of codebase.
ReactJS Documentation priories JSX:
ReactJS documentation uses JSX everywhere so JSX is only going to become more powerful.
Very useful tools and resources:
Babel is a tool able to transpiles ES6, ES7(stage 1 flag), JSX altogether.

Integrations with other frameworks

JSX simple example with AngularJS:
You can integrate JSX preprocessor with Angularjs to write the templates in places that you use javascript, for example in the directives.
If you want to use JSX-style with AngularJS the way is through AngularJS directives. In order to achieve this goal, we have angular-jsx library to convert templates into strings that Angular can understand. Take a look to this example:

Input

 
angular.module("foo").directive("bar",
    function() {
        return {
             // it can be used in the template for the directives
            template: <div>This is a simple example.</div>
        };
    }
);

Output

 
angular.module("foo").directive("bar",
    function() {
        return {
            template: "<div>This is a simple example.</div>"
        };
    }
);

More information about it can be found here. If you want a deeper point of view about more technical aspects related to ReactJs and JSX maybe this article will do the trick for you.

Redux with React – First look

redux with react
This time I going to take the time to research and write about Redux in combination with React, one of the hottest libraries for front-end web development. It was created in 2015, influenced by Flux architecture and became popular very quickly because of it’s simplicity, excellent documentation and size (2 KB). Also is very easy to use redux with react. Let’s start with the basics:

What is Redux?

According to the official site Redux is defined as a predictable state container for JavaScript apps. Basically Redux maintains the state of an entire application in a single immutable state tree (object). This object can’t be changed directly. When something changes, a new object is created (using actions and reducers). The main goal of Redux is to facilitate the task of connect sources of different environments like for example APIs and sockets.

Redux with React.

Redux is kind of ‘created’ to work with React.js but also can be used with Angular.js, Backbone.js or just vanilla JS.

How to install it?

To install the stable release (through npm as package manager with a module builder like Webpack or Browserify to use modules of CommonJS):
npm i -S redux
Also you may want to install the connection to React and the developer tools.
npm i -S react-redux
npm i -D redux-devtools

Core concepts of Redux

1 – Actions.
The actions, summarized actions are events. The action task is to send data from the application (user interactions, internal events such as API calls, and form submissions) to the store. The only way to pass information to the store is through actions. The actions are POJO (Plain Old JavaScript Objects) with at least one property that indicates the action type and, if necessary, others properties indicating any other necessary data to do the action. Normally they use the format defined in FSA.

An action example:

 
{
    type: 'TODO_APP',
    payload: {
        text: 'How to learn Redux,
    },
}

Actions are created with action creators. They are just functions that return actions.

 
function myAction(someText) {

return {
	type: TODO_APP,
	payload: someText
}
}

To call an action anywhere in our app must be through dispatch method, like this:

 
// to send an action to the Store (The concept of Store will be seen ahead).
Store.dispatch (myAction(someText)); 

2 – Reducers.

While the actions describe that ‘something’ happen they don’t specify how our app reacts to that ‘something’. In Redux, reducers are functions (pure, I will explain what a pure function is later) that take the current state of the application and an action and then return a new state.
(prevState, action) => nextState
Here is a very simple reducer that takes the current state and an action as arguments and then returns the next state:

 

function handleAuth(state, action) {
	return _.assign({}, state, {
		auth: action.payload
	});
}

Some things you should never do in a reducer:
Modify the arguments directly (the right way is to create a copy first.)
Do actions with secondary effects like API calls or change a route.

The name we put to the reducer is used as property of ‘store’ we created and is where will be saved the state returned from the reducer.

3 – Store
Store is the object that holds the application state and provides a few helper methods to access the state, dispatch actions and register listeners. The entire state is represented by a single store. Any action returns a new state via reducers.
The store has four main responsibilities:
Store the global state of the app.
Give access to the state through store.getState()
Allow the update of the state through store.dispatch()
Register listeners through store.subscribe(listener)
Take this as example:

 

import { createStore } from 'redux';

	let store = createStore(rootReducer);
	let authInfo = {username: 'alex', password: '123456'};
	store.dispatch(authUser(authInfo));

This image illustrates the work flow of Redux.

redux dataflow
Redux data flow (Image: Tanya Bachuk)

The three principles of Redux.

– Single data source: The app state stores in one objet tree inside a unique STORE.
– The state is read only: The only way of change the state is through ACTIONS.
– Changes are made with pure functions: To specify how the state tree is transformed by actions, you write pure reducers.

Where can Redux be used?

Contrary of what you may be thinking, the only use of Redux isn’t with React. It can be integrated with any other library/framework like for example Vue.js, Polymer, Ember, Backbone.js or Meteor, but Redux plus React, though, is still the most common combination.

Integrating Redux with React: Installing react-redux

The connection of Redux with React isn´t included directly inside Redux, in order to achieve this, we need to download react-redux:
npm i -S react react-dom react-redux redux

Encapsulating the app.

First we need to encapsulate our app with the component Provider that comes with react-redux. This component receives a unique parameter called store which one is the instance of the STORE we are using. See the follow example.

 
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import React from 'react';
import store from './store';
import App from './components/App';

render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('app')
);

This component Provider defines in the global context of React our instance of store.

Accessing the store.

Now is time to define what components are going to Access our Store, because not all of them will need to. In order to do that we need to connect our Redux components to Redux, this can be achieved with a decorator that came with react-redux called connect.

 
// Importing the decorator @connect of react-redux

import { connect } from 'react-redux';
import React from 'react';
import UserItem from './UserItem';

// Aplying the decorator @connect to our component.

@connect()
class UserList extends React.Component {
  render() {
    // Rendering the user list we receive from Store  .  
    return (
      <section>
        {
          this.props.users
            .map(user => <UserItem {...user} key={user.id} />)
        }
      </section>    
    );
  }
}
export default UserList;

This way our component UserList will have inside it props all the data of the Store. With this we can render our app using the data stored in the Redux Store.

Pure functions vs Impure functions:

Pure Functions
A function is considered pure if:
a) It always returns the same value when given the same arguments.
b) It does not modify anything (arguments, state, database, I/O, ..).

Examples of Pure Functions (in JavaScript):

 
function add(x, y) {
return x+y;
}
 
function getLength(array) {
return array.length;
}

Impure Functions

A function is considered impure if it is not pure, typically because:
a) it makes use of an external or random value. (It stops being entirely contained and predictable.)
b) It performs an external operation, in other words it causes side effects.

 
var x = 5;
function addToX(a) {
return a+x; / Use of an external variable
}

Example: A complete reducer with tests (can use a library for this like Expect.js).

You might be interested in:

First look to javascript unit test framework – ExpectJs

 

const counter = (state = 0, action) => {

  switch (action.type) {
    case 'INCREMENT':
      return state + 1;
      
    case 'DECREMENT':
      return state - 1;
      
    default:
      return state;
  }
}

expect(
  counter(0, {type: 'INCREMENT'})
).toEqual(1);

expect(
  counter(1, {type: 'INCREMENT'})
).toEqual(2);

expect(
  counter(2, {type: 'DECREMENT'})
).toEqual(1);

expect(
  counter(1, {type: 'DECREMENT'})
).toEqual(0);

expect(
  counter(1, {type: 'DECREMENT Else'})
).toEqual(1);


expect(
  counter(undefined, {})
).toEqual(0);

console.log('Tests passed!');

Why would I need to use Redux? (extracted from this article)

Predictability of outcome:
There is always one source of truth, the store, with no confusion about how to sync the current state with actions and other parts of the application.
Maintainability:
Having a predictable outcome and strict structure makes the code easier to maintain.
Organization:
Redux is stricter about how code should be organized, which makes code more consistent and easier for a team to work with.
Server rendering:
This is very useful, especially for the initial render, making for a better user experience or search engine optimization. Just pass the store created on the server to the client side.
Developer tools:
Developers can track everything going on in the app in real time, from actions to state changes.
Community and ecosystem:
This is a huge plus whenever you’re learning or using any library or framework. Having a community behind Redux makes it even more appealing to use.
Ease of testing:
The first rule of writing testable code is to write small functions that do only one thing and that are independent. Redux’s code is mostly functions that are just that: small, pure and isolated.
Pure functions:
return a new value based on arguments passed to them. They don’t modify existing objects; instead, they return a new one. These functions don’t rely on the state they’re called from, and they return only one and the same result for any provided argument. For this reason, they are very predictable.
Because pure functions don’t modify any values, they don’t have any impact on the scope or any observable side effects, and that means a developer can focus only on the values that the pure function returns.

CONCLUSION

Redux has a growing popularity and is even bigger every day. Companies like Uber and Twitter and projects like WordPress are using it successfully in production. Redux isn’t a perfect fit for everything but we recommend to check it out. If you are up to it you can deep your knowledge over here, a tutorial from the Redux creator and see this example contains source code of Todo List app using Redux with React.

How to copy to clipboard using JavaScript

It is amazing how modern browsers had evolved, and how powerful they became we got to a point where we don’t need flash anymore.
A time ago the only way to copy to browser’s clipboard was from a button in the app using Flash, but with modern browsers we can achieve copy to clipboard using javascript, without using any plugin. First, let’s set the ground of what the clipboard is…

copy to clipboard using JavaScript

The clipboard is basically a place for storing and retrieving a single piece of cloned data, by data means from a simple string to a whole directory. There can be more than one clipboard present, for example, the “operative system clipboard”, it would be less difficult if all the applications were able/created to use the operative system clipboard, but unfortunately this is not always the case. For example, virtual machines, unless you explicitly turn on a clipboard integration option.
Following the same behavior are the web apps. Web applications runs in a sandbox environment, it restricts access to file system and the system clipboard, for security reasons. This article expose why the system clipboard is a restricted resource.
Fortunately, there ways to bypass those restrictions and gain access to system clipboard using JavaScript. This is post is about show several ways to do it.

Copy to clipboard using JavaScript

Example 1 (vanilla JavaScript):

This solution is a simple one but has some drawback because you must add an <input> or <textarea> element with the text to be copied to the DOM. The command used ‘execCommand’ allows us to execute other commands like cut, copy or paste.

The input or textarea to receive text you want to copy:

 
<input name="exampleClipboard" placeholder="Insert the text you want to copy" value="Example text" tabindex="1" autocomplete="off" maxlength="240" style="width:200px" type="text">
<p>
  <button id="copy">
    Copy text
  </button>
</p>
<p>
Right click paste or Ctr + v after click Copytext button <br/>
<textarea></textarea>
</p>

The function to call:

 

<script>
function copyToClipboard() {
document.querySelector('input').select();
document.execCommand('copy');}
</script>

The button:

 
<button id="howToCopyClipboard" onclick="copyToClipboard()">Copy</button

*You can change the input label for a textarea if you want. Keep in mind that this solution forces you to keep a maybe non desire input or textarea element in your page.

 
Try yourself

Example 2 (vanilla JavaScript):

This is a more elaborated solution where we validate compatibility with browsers. For this solution lets create a function that copies a string to the clipboard, this function must be called from within an event handler such as click. More reference to this method can be found here you can see a practical example here.

 

function copyToClipboard(text) {

if (window.clipboardData && window.clipboardData.setData) {
 // IE specific code path to prevent textarea being shown while dialog is visible.

return clipboardData.setData("Text", text); 

} 

else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
        var textarea = document.createElement("textarea");
        textarea.textContent = text;
        textarea.style.position = "fixed";  // Prevent scrolling to bottom of page in MS Edge.
        document.body.appendChild(textarea);
        textarea.select();
        try {
            return document.execCommand("copy"); // Security exception may be thrown by some browsers.
        } catch (ex) {
            console.warn("Copy to clipboard failed.", ex);
            return false;
        } finally {
            document.body.removeChild(textarea);
        }
    }
}

Example 3 (with a library): Clipboard js

It would be overwhelm to have to write validations for browser compatibility, etc, so Lets avoid reinvent the wheel and use a library that manages all this for you. ClipboardJs is very easy to use, here is an example:

 
<!-- Target -->

<input id="textToCopy" value="Any text you want to copy">

 

 

<!-- Trigger -->

<button class="btn" data-clipboard-target="#textToCopy">Copy to clipboard
</button>

Notice that

 data-clipboard-target 

do the job here. Let’s see another feature but this time is to cut instead of copy.
The only change needed is to add

 data-clipboard-action="cut"> 

like this:

  
<textarea id="textToCopy">Another feature … </textarea>
  
<!-- Trigger -->
<button class="btn" data-clipboard-action="cut" data-clipboard-target="#textToCopy">
    Cut to clipboard
</button>

More reference about this useful library can be found here.

Try yourself

At the end there isn’t universal solution to this task, out there are a lot of solutions in many different ways with just JavaScript (or JavaScript libraries without involving Flash), feel free to use the most suited for you.

First look to javascript unit test framework – ExpectJs

Today I going to write about javascript unit test frameworks, to be more specific, about Expectjs.
Sometimes web developers ignores the action of testing their code, automated, just because it works in
some random manual attempts. Just a reduced number of developers really like the activity of write unit test because of the security and the mind peace it brings to any development process.
This time let’s take a look at ExpectJS, a minimalistic BDD assertion toolkit based on should.js that
provides very useful features to developers in order to test their codes through unit test. But how it
works exactly? In this post I’d like to expose the main features and APIs of this amassing library.
 
javascript unit test framework

Two definitions before go to the main topic: Assertions + Unit Testing with ExpectJs

Basically an assertion is a statement where a Boolean-valued function is expected to be true at that
point in the code. If the assertion evaluates to false in some point of the execution, it will throw an
assertion exception. For example:

 
function assert(condition, message) {
    if (!condition) {
        throw message || "Assertion failed";
    }
}
 

In the other hand, a unit test checks blocks of code to ensure that they all run as expected. Simple JavaScript unit test will take a function, monitor output and return its behavior, and assertions are used in the process. Sometimes this task is not so easy with vanilla JavaScript.

Other javascript unit test frameworks

There are other options. Out there are plenty of javascript unit test frameworks like QUnit, Sinon, Mocha or Jasmin, all of them are able to integrate assertions libraries like ExpectJS.

Let’s get starting with ExpectJS

How to install it.
 
Node
Install it with NPM or add it to your package.json:
$npm install expect.js
Then you can use the following code:

var expect = require('expect.js');

Browser

<!-- download the file to your local -->
<script src="expect.js"></script>

<!-- from a CDN -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/expect.js/0.2.0/expect.js">
</script>

 

Main features

– Cross-browser: works on IE6+, Firefox, Safari, Chrome, Opera.
– Compatible with all test frameworks.
– Node.JS ready (require(‘expect.js’)).
– Standalone. Single global with no prototype extensions or shims.

Our first test

Let’s say we want to test the following add function:

function add(a, b) {
return a – b; 
};

expect(add).to.be.a('function');  // this assertion passes
expect(add(1, 3)).to.equal(4);  // this assertion fail
expect(add(5, 2)).to.be.lessThan(8); // this assertion passes

Now, notice that if we execute this code, and we check the console of the browser you’ll see an error for the assertion that failed (the second one).

 
Try it yourself

The previous approache is not too intuitive, so lets wrap it up with a framework that offers a more visual result, lets use MochaJs:

Comparing with other assertion test frameworks

Differences with should.js
– No need for static shouldjs methods like should.strictEqual(). For example, expect(obj).to.be(undefined) works well. More intuitive now!
– Some API simplifications/changes.
– API changes related to browser compatibility.

Let’s see how intuitive the ExpectJS API’s can be.

Example 1: a/an: asserts typeof with support for array type and instanceof (used with mocha testing framework)

describe("Example 1", function() {

 var n;
 var cars;

it("number check", function() {
    n = 'good';
    expect(n).to.be.a('number');
  });


  it("array and object check", function() {
    cars =['Mercedes', 'Toyota', '4x4'];
  
   expect(cars).to.be.an('array'); // it works
   expect(cars).to.be.an('object'); // it Works too since it supports typeof
  });
});

Example 2: match: asserts String regular expression match. We can use useful regular expressions like this:

describe("Regular expressions check", function() {
 var version;
it("version check", function() {
    n = '4.8.2';
    expect(version).to.match(/[0-8]+\.[0-8]+\.[0-8]+/);
  });
});

Try it yourself

Other resources the API provides:

ok: asserts that the value is truthy or not.

expect(1).to.be.ok();

eql: asserts loose equality that works with objects.

expect({ a: 'b' }).to.eql({ a: 'b' });

contain: asserts indexOf for an array or string.

expect([1, 2]).to.contain(1);

length: asserts array .length.

expect([]).to.have.length(0);

empty: asserts that an array is empty or not.

expect([]).to.be.empty();

property: asserts presence of an own property (and value optionally).

expect(window).to.have.property('expect')

key/keys: asserts the presence of a key. Supports the only modifier.

expect({ a: 'b' }).to.have.key('a');

throw/throwException/throwError: asserts that the Function throws or not when called.

expect(fn).to.throw(); // synonym of throwException.

withArgs: creates anonymous function to call fn with arguments.

expect(fn).withArgs(invalid, arg).to.throwException();

within: asserts a number within a range.

expect(1).to.be.within(0, 100);

greaterThan/above: asserts.

expect(3).to.be.above(0);

lessThan/below: asserts.

expect(0).to.be.below(3);

fail: explicitly forces failure. (This is very helpful sometimes).

expect().fail()

How to use it with spies.

A way to verify the function behavior in unit test is through the use of spies. A spy allows you to monitor a function exposing options to track invocation counts, arguments and return values. The main principle here is that it replaces a particular function where you want to control its behavior in a test, and record how that function is used during the execution of that test (similar to how actors are replaced with stunt doubles for dangerous action scenes in Hollywood movies).

Let’s see how it works: (Other examples can be found here)

spyOn(foo, 'bar');  // Here the spyOn method takes an object and a method to be spied upon.
foo.bar(1);         // Call the function
 
expect(foo.bar).toHaveBeenCalled(); // Run assertions with ExpectJS.
expect(foo.bar).toHaveBeenCalledWith(1);

Final considerations.

ExpectJS is a very useful assertion library and combined with other javascript unit test frameworks can be very visual and can save a lot of time while provide security to your code. Other libraries similar are Chai, should.js, and better-assert. One of the advantages is that it is Standalone and can be integrated with any javascript unit test frameworks.

References:

https://github.com/Automattic/expect.js/blob/master/README.md
https://abdulapopoola.com/2016/04/11/how-function-spies-work-in-javascript/
https://designmodo.com/test-javascript-unit/

TinyMCE Validating length AngularJs

 
 

I’m creating this “how to…” tutorial based on my experience working with TinyMCE Validating length with Angularjs, and the answers I found in the internet community Stack overflow and github.

What is TinyMce:

It is an opensource WYSIWYG (What You See Is What You Get) HTML editor designed to simplify website content creation. In other words it is a rich text web editor. This is the official website https://www.tinymce.com/

TinyMCE Validating length

TinyMCE Validating length using AngularJs

For the first example I used TinyMCE v4.3.3 with angular-ui-tinymce v0.0.12 plugin and AngularJS v1.4.6.

In the AngularJs controller we have to set the config options, and in the view we use a textarea with the parameter ui-tinymce=”tinymceOptions”


angular.module('myApp', ['ui.tinymce'])
.controller('myCtrl', ['$scope', function($scope) {
    
//set the config options
 $scope.tinymceOptions = {
                    plugins: 'code',
                    toolbar: 'undo redo | bold italic | styleselect | code',
                    menubar: false,
                    forced_root_block: false
                };
// ...
}]);

 
 

<textarea ui-tinymce="tinymceOptions" ng-maxlength="100" 
name="editor" ng-model="vm.editor">
</textarea>
<span ng-show="form.editor.$error.maxlength" class="error">
    100 character limit reached!
</span>

 
 
The code above will not work as it is, because of a known bug https://github.com/angular-ui/ui-tinymce/issues/145

Work around

Took from StackOverflow
One work around can be to disable SCE mode with this code .config([‘$sceProvider’, function($sceProvider) {
$sceProvider.enabled(false);
}])
but…

Beware of security vulnerabilities!

Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain contexts to result in a value that is marked as safe to use for that context. With SCE disabled, an AngularJS application allows to render arbitrary HTML into the div, and rendering user controlled input creates security vulnerabilities.

 
 

angular.module('myApp', ['ui.tinymce'])
.config(['$sceProvider', function($sceProvider) {
    $sceProvider.enabled(false);
}])
.controller('myCtrl', ['$scope', function($scope) {
    
//set the config options
 $scope.tinymceOptions = {
                    plugins: 'code',
                    toolbar: 'undo redo | bold italic | styleselect | code',
                    menubar: false,
                    forced_root_block: false
                };
// ...
}]);

 
 
Here is the JsFiddle https://jsfiddle.net/naXa/zsnLupvd/

Another work arround

This is a directive written by @andresmatasuares for TinyMCE Validating length with AngularJs.

app.directive('plainTextMaxLength', function($filter) {
    return {
      restrict: 'A',
      require: 'ngModel',
      link: function(scope, element, attributes, ngModel) {
        var maxLength, validPlainTextLength;
        validPlainTextLength = function(v) {
          if (!v) {
            return true;
          }
          return stripHtmlTags(v).length <= maxLength;
        };
        maxLength = void 0;
        scope.$watch(attributes.plainTextMaxLength, function(newValue, oldValue) {
          if (maxLength !== newValue) {
            maxLength = newValue;
            return ngModel.$validate();
          }
        });
        return ngModel.$validators['plainTextMaxLength'] = function(modelValue, viewValue) {
          if (viewValue.$$unwrapTrustedValue) {
            return validPlainTextLength(viewValue.$$unwrapTrustedValue());
          } else {
            return validPlainTextLength(viewValue);
          }
        };
        
      }
    };
  });

 
Here you can find the plunker code http://plnkr.co/edit/oAZcHZAmCXYOTckJCPcs?p=preview

How to use filters within controllers in AngularJs (mini-challenge 12)

filters within controllers

Filters within controllers (mini-challenges 12)

AngularJs Mini-Challenges is a growing collection of “Challenges” about the most quirky parts of the AngularJs framework. It encourage you to find and fix common mistakes and subtle bugs, as well as performance issues and bad practices, that non-expert AngularJs programmers may encounter on their endeavours into the depths of the framework.

AngularJs Mini-Challenges does not aim to teach you AngularJs. Former knowledge of the Framework is strongly recommended in order to understand the topics covered in this Challenges. In order to learn the basics of the Framework, please head over to this excellent book:

 

book

Book Tip

ng-book – The Complete Book on AngularJS
Ready to master AngularJS? What if you could master the entire framework – with solid foundations – in less time without beating your head against a wall?


Amazon

 

The Challenge:

How would you use filters within controllers like “filter” in JavaScript? And how to create a custom filter?
For example in the html you can use filter’s filter to do a search in a list of elements:

 <tr ng-repeat="friend in friends | filter:searchText">

<table id="searchTextResults">
<tr>
<th>Name</th>
<th>Phone</th>
</tr>

<tr ng-repeat="friend in friends | filter:searchText">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
</tr>
</table>

 
 

Solution:

In AngularJs you can inject the $filter service within the controller, and use it with the following syntax for “filter”:

$filter('filter')(array, expression, comparator, anyPropertyKey)

 

function myController($scope, $filter)
{
   $scope.result = $filter('filter')($scope.arrayOfObjects, $scope.searchCriteria);
}

You can also use other AngularJs filters Build-in like:

 $scope.formatedDate = $filter('date')($scope.date, "yyyy-MM-dd");
 $scope.result = $filter('lowercase')($scope.name);

You can find here a list of build-in AngularJs filters:
https://docs.angularjs.org/api/ng/filter

 
 
Filter Example with pipe in the HTML:

 
 
Filter example within the controller using Javascript:

 
 

How to create custom filters in AngularJs

AngulrJs have a build-in method to register custom filters, using the same approach you can use when you register a controller, a service and factories. See following example:

var myApp = angular.module('myApp', []);
app.filter('myFilter', function() {
  return function(input, option1, option2) {
    var output;
    // Logic to make your filter works.
    return output;
  }
});

 
for more reference about how to create a custom filter you can refer to https://scotch.io/tutorials/building-custom-angularjs-filters
 

Angular 2 seed for Visual Studio 2015

Angular 2 seed for Visual Studio 2015

This Angular 2 seed for Visual Studio 2015 targets Angular version 2.1.0 released on Oct 12, 2016. This project is based on official Angular2 Seed project. It relies on TypeScript and SystemJS.

angular 2 seed

Instructions:

-1 Clone or fork the repocitory.
https://github.com/jomendez/AngularJs-2-Visual-Studio-2015
-2 Make sure you have node installed, this code require node v5.x.x or higher and npm v3.x.x or higher, to check what version you are using run node -v and npm -v, in your cmd console.
-3 Open a cmd console, and go to your project root file location and run npm install to install dependencies

npm behind a corporate proxy

If you are trying to setup the seed behind a proxy, you migth encounter issues of connection refuced, etc. You can use the following command:
With password:

npm config set proxy=http://<username>:<pass>@proxyhost:<port>
npm config set https-proxy=http://<uname>:<pass>@proxyhost:<port>

or without password:

npm config set proxy=http://proxyhost:<port>
npm config set https-proxy=http://proxyhost:<port>

 

Fixing errors when using resharper

If you don’t have installed resharper in your computer please ignore this section, if you have it intalling, resharper migth cause cause some sintax error validation.

Error:
“Typescript Feature 1.5. Current language level is 1.4”.

Solution:
Resharper setting. From the menu bar in VS2015 -> Resharper -> Options -> Code Editing -> TypeScript -> Inspections -> Typescript language level, change to 1.5

Error:
Symbol ‘component can not be properly resolved, probably its located in an inaccessible module’

Solution:
You can disabled resharper’s typescript inspection for now.
Resharper > Options > Code Inspection > Settings
Find ‘File masks’ (bottom right) and add *.ts

 

Browser support

The Angular 2 seed runs on all major browsers including Internet Explorer 11+, Edge, Firefox, Chrome, Opera and Safari.

License

The Angular 2 seed is released under the MIT license.

Styling External Links in your site with CSS

Are you looking for an easy way to style and denote external links in your web site or blog, it is always good for the user to know when they are going to navigate away from your page, enriching the user experience. Perhaps most of the sites out there achieve this by placing code on the Back End. Here I going to share with you what I found on this topic, and how to do it just using CSS.

Clicking on external links, navigating away..

denote external links

We are going to use CSS selector to apply styles to all the “a” (anchors) except for internal links. This is translated into code like this:

a[href*="//"]:not([href*="mywebsite.com"]) {
    /* css code here  */
}

 

Notice that we combined the selector with some regular expression, the * mean select all elements, for a full list of selectors, you can visit:
http://www.w3schools.com/cssref/css_selectors.asp

Now, you can combine this selector with the ::after of the <a> element to include for example an icon that might looks like the externals links on Wikipedia.
(from http://www.w3schools.com/)
after browser suport

Although Wikipedia doesn’t use this approach, they use a class instead to insert the icon at the end of the external links, this should be done manually. With the method exposed here all the externals links will be styled automatically when the page loads.
external links wikipedia

 

book

Book Tip

CSS Mastery
Fully updated to the latest CSS modules, make the journey to CSS mastery as simple and painless as possible. This book dives into advanced aspects of CSS-based design, such as responsive design, modular CSS, and CSS typography. Through a series of easy-to-follow tutorials, you will learn practical CSS techniques you can immediately start using in your daily work.
Amazon

 

Here is a working example of how all the external links are decorated with the Wikipedia’s external link icon

a[href*="//"]:not([href*="example.com"]):after {
    margin-left: 3px;
    content: url(data:image/svg+xml,%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%22%20standalone%3D%22no%22%3F%3E%3Csvg%20xmlns%3D%22
http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2212%22%20height%3D%2212%22%3E%3Cpath%20fill%3D%22%23fff%22%20stroke%3D%22%2306c%22%20d%3D%22M1.5
%204.518h5.982V10.5H1.5z%22%2F%3E%3Cpath%20d%3D%22M5.765%201H11v5.39L9.427%207.937l-1.31-1.31L5.393%209.35l-2.69-2.688%202.81-2.808L4.2%202.544z%22
%20fill%3D%22%2306f%22%2F%3E%3Cpath%20d%3D%22M9.995%202.004l.022%204.885L8.2%205.07%205.32%207.95%204.09%206.723l2.882-2.88-1.85-1.852z%22%20fill%3D
%22%23fff%22%2F%3E%3C%2Fsvg%3E)
    }

Also you can denotate all the links that navigate away from your page even internal links that get open in another tab or windows:

:not compatibility

One last thing to keep in mind when you use this approach is the browser compatibility with the :not css selector, for example Internet Explorer starting supporting it from version 9:
(from http://www.w3schools.com)
not css selector browser compatibility

Ultimately, for the no compatible browsers you can detect the browser version with JavaScript or Jquery and then select all the external links and apply the style using JavaScript code:
Jquery Example:

$(function() {
  $('a').each(function(i, e) {
    if ($(e).attr("href") && ($(e).attr("href").indexOf("http://") > -1 || $(e).attr("href").indexOf("https://") > -1)) {
      $(e).css({
        "background-image": "linear-gradient(transparent,transparent),url(data:image/svg+xml,%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%22%20standalone%3D%22no%22%3F%3E%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2212%22%20height%3D%2212%22%3E%3Cpath%20fill%3D%22%23fff%22%20stroke%3D%22%2306c%22%20d%3D%22M1.5%204.518h5.982V10.5H1.5z%22%2F%3E%3Cpath%20d%3D%22M5.765%201H11v5.39L9.427%207.937l-1.31-1.31L5.393%209.35l-2.69-2.688%202.81-2.808L4.2%202.544z%22%20fill%3D%22%2306f%22%2F%3E%3Cpath%20d%3D%22M9.995%202.004l.022%204.885L8.2%205.07%205.32%207.95%204.09%206.723l2.882-2.88-1.85-1.852z%22%20fill%3D%22%23fff%22%2F%3E%3C%2Fsvg%3E)",
        "background-repeat": "no-repeat",
        "padding-right": "13px"
      });
    }
  });
});

 

Working example:

Market yourself Put your name out there

Market yourself

It is very important to put your name out there (using several resources like a blog, github, stackoverflow, etc)  in order to market your self, specially when you moved to the U.S and you haven’t work for a company here, even if you did, still very important to communicate to your potential employers that you love what you do and you dedicate time of your free time to keep improving your skills by for example contributing to github open source project, or answering questions on stackoverflow, etc. Create you own blog is another way to market yourself, among other benefits you’ll learn to deal with criticism, you might get feedback from new people, You’ll have the opportunity of practice your written English and become a better writer, you will help other people, etc.


 

Get your own resources

get your own resources market yourself

Github.com

You can either create your own projects (maybe univercity projects) or contribute to someone else’s project, the idea is to collaborate and share. Here is an excellent guide to how to contribute to github projects http://kbroman.org/github_tutorial/pages/fork.html

 

stackoverflow.com

Stackoverflow has become an essential tool for developers with millions of answer to different issues/situation for a day to day of a developer, has become a tool of knowledge where you can find your answer already or ask a question there’s going to be somebody ready to answer your question. You can become one of this person that uses your knowledge to help others sharing what you learn product of your experience. Also when you register in stackoverflow  you can create a profile where employers can find you and send you job offers.

 

Your own blog

Blogging is another tool to market yourself. There is a lot of resources to create your own blog, the two more popular services are www.blogger.com and https://wordpress.com/ you can create and host you blog for free with this two services, if you want more flexibility in the functionalities you can add to your blog or more control on the look and feel, I’ll suggest you, to buy a hosting, I use wordpress with godaddy for this blog, also I’ll suggest you to buy your own domain, for example yourname.com or yourname.me. If you still not convinced I’ll recommend this article: http://www.thomashanning.com/10-reasons-you-should-blog-as-a-developer/

 

book

Book Tip

Soft Skills: The software developer’s life manual
Soft Skills: The software developer’s life manual is a unique guide, offering techniques and practices for a more satisfying life as a professional software developer


Amazon

 

 

Connect with people near you

It is very important that you connect with other folks, doing this you might be opening doors to future jobs opportunities, you can use Linkedin to find other developers and managers near you, also you can use the meetups as a resource to meet people. I hardly recommend that before you apply to a job, research about it, look for the managers of the group you are applying, try to connect with them, you can use Tweeter, Linkedin, etc. You can ask for advises, make thoughtful tweets, ask them about the position they have open, etc. When you connect with them before you get the interview this might play in your favor.

 

 

Your resume

Your resume is your more important marketing tool, the content of your resume it’s provably the first thing hiring managers are going to learn about you, and it might open or close you the door to an interview, that’s why it is very important to create a very pleasurable first impression. There are few rules of what a recruiter or hiring manager will spect from your resume:

https://www.livecareer.com/resume-examples/it/software-engineer (online tool to create your resume)

http://www.techrepublic.com/blog/10-things/10-tips-for-writing-a-job-winning-developer-resume/

http://www.businessinsider.com/how-to-write-a-developer-resume-that-will-get-you-hired-2014-11?op=1

 

 

Prepare yourself for interviews

The interview is the next step in your journey to land in a job as software developer or related field, it is very important that you prepare yourself. Here are few websites where you can find useful information about interviews specifically within the software development field. Also in the book I suggested above there are several tips for interviews. Here you can find some useful links.

http://www.infusivesolutions.com/blog/bid/97934/10-Job-Interview-Tips-for-Software-Developers

https://www.coursera.org/learn/cs-tech-interview

https://www.youtube.com/watch?v=E88P7tQhMvI

http://www.programmerinterview.com/index.php/job-advice/how-to-prepare-for-a-software-engineering-interview/

 

Learn, Prepare yourself (Guide for U.S Immigrants)


 

Getting started:

This is one of the few careers that is highly pay and you don’t need a licence though, but you need to prove that you know and are able learn and perform the job with high standards. That’s the biggest advantage of the software developer career or related fields you don’t need a degree certificate, a diploma or a license to be able to work on this field, your knowledge and your experience should be sufficient to be able to find a job. I’m not saying that trying to get a degree is bad, if you want to go to the university and get your degree that’s fine, but it is not mandatory when you are looking for a job as a software developer.
If you still thinking that it is not worth the effort to trying to re-orientate or continue your career as a software developer or related field in the USA, I encourage you to do a quick search on salaries on the internet, this might not be 100% accurate but at least will give you an idea of how much you could worth, you can check this site for salary research:

http://www.indeed.com/salary/Estimator.html
https://www.glassdoor.com/Salaries/index.htm
https://www.roberthalf.com/workplace-research/salary-guides

These are few from the many websites in internet that might help you to investigate what is an average salary for a Software developer or related field.

 

Your English is a must:

learn English

You might be wondering why this guide is written in english, it is because even though the target audience of this material are immigrants, the first step to a successful career in this country is to learn english, if it is not your first language of course.
If you were born in USA, or any English speaking country, or have an excellent domain of the English language, then, you can skip this section. If not this is very important for you, first thing you should do, before you even think of apply for a job, is perfectionate your english or start learning it if you are in cero. Not only because you most likely will be interacting with others at your company in english, but also because a great number of good resources to learn and also the tools you might be interacting with, are going to be in english.

Here are some resources you can use to learn or perfectionate your english:
You can go to college to take ESOL (English for Speakers of Other Languages) class.
If you are starting learning and you want to learn by yourself I recommend you Rosetta Stone
If you are more advanced, then I highly recommend Open English (www.openenglish.com)
www.engvid.com (free and muy bueno)

 

Productivity and inspiration

Productiviti And Inspiration

Productivity: If you are starting you career as a software developer or related field here in the USA or are planning to continue your career here, whichever is your case, you need to be productive and get the most of the time you have available. I don’t know why but I found out that living in this country it is like going hight speed on the expressway, and the time just flies. Being productive means that you are highly effective in a relatively short period of time. One of the most important things in this career is to be prepared and possess as much knowledge as possible in your field, remember, you’ll probably have to compete with very talented people for job opportunities. I strongly believe that the main thing you need to do to improve your productivity is define your goals and plan your actions to achieve those goals.
One technique I use to be focus and improve my performance when I studying or developing software is the pomodoro technique, click here to learn more. In general you can visit this blog post with advices of how to be productive, however this post is more focused to loud open spaces offices, but I guess you’ll extract the idea.
Also if you use chrome you can install this extension to pomodoro your time:
https://chrome.google.com/webstore/detail/pomodoro-timer/hfgjlgjnpkpmnpojkkpfkogapiclopop?utm_source=chrome-app-launcher-info-dialog

Inspiration: sometimes you’ll feel like you don’t want to do anything, that’s normal. It is very important for your productivity to overcome that stage. Look for things that inspires me, had helped me to keep focus and get back on track, for example I found very interesting the Ted Talks, these are some of my favorites:






Inspiration from books:

I consider books a key source of knowledge, as a matter of fact I think it is the main source of knowledge. For me I prefer to listen an audio book (of course, when it is not code examples involved, etc.), I use to drive almost one hour to work, I like to drive while listen an audiobook, also at the gym, when I’m working out. For me it is a bit hard to allocate time to read a paperback book. Also audible offers a monthly subscription of $14.95 a month. Receive 1 credit each month, with that credit you can purchase any audiobook you want (I have this subscription myself).

Click here to subscribe to Audible
These are some of my favorites audiobooks for inspiration:


 

Learn, learn and learn

learn Learn Learn

This is perhaps the most important thing a software developer needs to do to start/maintain and built a successful career. These are some resources to free to learn or sharpen your development skills:
https://www.codecademy.com/
https://www.hackerrank.com/
https://mva.microsoft.com/
https://www.coursera.org/

Some paid services to learn:
https://www.pluralsight.com/
https://www.lynda.com/
https://teamtreehouse.com/
https://www.udemy.com/

Certifications:
There are many opinions on certifications, some managers would like candidates with certification some don’t, In my opinion, possessing a certification doesn’t guarantee that you are going to obtain the job, however it might make the difference between two candidates with the same experience and skill sets, I see certifications as milestones for when I want to learn something new or improve my knowledges in certain technology, When I studying for a certification I like to study to learn deeply first and after that I start thinking on the exam, just my opinion. I totally recommend and encourage you to do certifications, it is a way to study for an end objective (the exam) it is always good to have a little bit of pressure and a deadline, to avoid procrastination.

These are some of the certification, you should research in your field for the certification that suit you:

Scrum:
https://www.scrumalliance.org/certifications/practitioners/certified-scrummaster-csm

Microsoft technologies (Web, Mobile, Desktop, DB, Application lifecycle, etc):
https://www.microsoft.com/en-us/learning/certification-overview.aspx

Java:
http://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=458&get_params=p_track_id:JSE7PROG

PHP
http://www.zend.com/en/services/certification

Books:

These are some of my favorites books (click on the images below):

Here click the link to obtain a complete list of
Microsoft Exam references

Some of my favorites technical books (some of them are free):

Javascript:
https://github.com/getify/You-Dont-Know-JS
http://speakingjs.com/es5/index.html

AngularJs:
https://www.ng-book.com/

Asp.Net

C#

I highly encourage you to do some research and find the best books in your field of expertise, you might be surprised of the many books offered for free. For more books, please contact me via tweeter @joMendezdev

Notes:
There are few programs that you might be eligible for, for example the WIOA program (Workforce Innovation and Opportunity Act) Where they can pay for your trainings and courses for your development
http://sitefinity.floridajobs.org/frequently-asked-questions-directory/wia-program-faq
Read the FAQs to get more information.

 

Follow the leaders, learn from them

Follow the Leader

The leaders can help you to stay on top of relevant news and trends and keep up to date in technology. Here is a list of the most relevant Front-End leaders. https://twitter.com/frontendrescue/lists/cool-people/members
Note: I encourage you to find the leaders on your field, follow them, learn from them, and with hard work you can become a leader.


 

Find the best resources (keep current)

find the best resources

In this career it is always important to be current, and be on top of the new frameworks, design patterns, good practices, etc. You should find you own resources in your field, for example daily news, magazines, blog post, etc.
One thing I do is that I subscribe to RSS feeds of the blogs that I’m interested on, here is an example of how you can do it on Outlook (animated gif):

add rss outlook guide

Here are few examples of some of the resources I use to keep current, in my case I look for resources related to .Nec/C#/Javascript/AngularJs etc.:
https://hackernoon.com/
https://medium.com/tag/javascript
http://blog.cwa.me.uk/
https://css-tricks.com/
https://www.smashingmagazine.com/

You’ll need to research and find your resources in your field.

 

Attend conferences

attend conference

Attending conferences is fun, you can meet other developers, in the meetups usually somebody give a speech about certain topic of interest, You can use meetup.com to find groups related to your interests:
https://www.meetup.com/find/?metaCategory=tech
I’m part of the DotNetMiami group, also, MiamiJs, among others. I hope I see you around in one of this groups one of this days.

Also there are some annual events like:

http://technightattheballpark.com/ which take place around august
The tech night at the ballpark it is more for meetup and networking, a lot of recruiters and companies go there to try to find talented tech prospective, and after that, enjoy the baseball game.

http://www.fladotnet.com/codecamp/ (this is awesome, you can’t miss this one)
Description taken from the website:
What is Code Camp? South Florida Code Camp is a FREE one day GEEK FEST held on Saturday February 18, 2017. This is the 13th year for South Florida Code Camp. The event will have speakers from the local community and beyond. Speakers will be presenting some of the most requested topics like Machine Learning, DotNet Core, Windows 10, Mobile Development, ASP.NET, Javascript, JQuery, Visual Studio 2015, MVC Framework, Sharepoint, SQL Server 2016, Xamarin, cross platform development and Azure. Code Camp is community driven by a group of dedicated volunteers and speakers. Breakfast and lunch is included!