Learning AngularJS Part 1/4

Prime Number Detector using ngClass

Posted on August 18, 2015 in webdev, angularseries
Note this is part of the "Learning AngularJS Series".
See a list of these projects here


Ever since I got my first job as a web developer, I've run across a few javascript libraries and frameworks. Backbone was the first one I encountered, but since then I've been attracted to others. If you google "Javascript Frameworks" you will find hundreds of results including jQuery, Prototype, MooTools, Foundation, React, and more.

For now I have decided to focus on AngularJS because from what I can tell, it does a good job of simplifying scary looking HTML documents by "data-binding" and creating "directives" which increase the potential of ordinary HTML elements. I believe it's a good introduction to MVC architecture and it's simple enough to encourage the beginning web developer.

I've decided to create a number of small "tools" that each illustrate a feature of AngularJS. Today I made a "prime number detector".

Using ngClass - Prime Number Detector

Angular has a directive called ngClass which lets you dynamically set CSS classes on an HTML element. In this case, the input from the textbox determines the style, or class, of the header below the textbox.

I set up one class called "prime" that makes the text green. When input is detected, angular runs the function "isPrime()" and returns a boolean. "True" triggers the prime class, while "false" removes the prime class if it is active.

Here is the html and the script that accompanies it:

You can see that the attributes “ng-app”, “ng-controller”, “ng-model”, and “ng-class” do most of the work. The value in the input gets passed into the main controller function through “$scope”. If the function isPrime() returns true, then “prime” will become the new class and jQuery will modify the text to be “Prime!”.

See it on Github

comments powered by Disqus