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: