Learning AngularJS Part 1/4

Prime Number Detector using ngClass

Posted on 2015-08-18 03:08:00 in webdev, angular

Intro

Ever since I got my first job as a web developer, I've come 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:

<div ng-controller="index" id="input">
    <input type="text" ng-model="value" class="form-control"/>
    <div>
        <h1 id="main_text" ng-class="{prime: isPrime()}">Not Prime</h1>
    </div>
</div>
angular.module("myapp", [])
.controller("index", ["$scope", function ($scope) {
    $scope.value = 1;
    $scope.isPrime = function () {
        for(var i = 2; i < $scope.value; i++) {
	    if($scope.value % i === 0) {
	        $("#main_text").text("Not Prime");
		return false;
            }
	}
	if ($scope.value > 1) {
	    $("#main_text").text("Prime!");
	    return true; 
	}
    };
}]);

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