Learning AngularJS Part 4/4

Word Reverser - Using $watch

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

Using $watch

I believe the beauty of MVC architecture is in the constant communication between the model, view, and controller. It was pleasing to see how easily the view renews itself with “$watch”. In the past I have used multiple javascript functions to update the DOM based on user input. “$watch” succinctly does all that for you.

I thought an easy way to implement this would be to create a live word-reverser. As you type the word, $watch updates the view to reverse the order of the letters you type.

Not much goes on in the html, other than basic value binding. Here is the javascript, which is very simple:

angular.module("myapp", [], function($interpolateProvider) {
    $interpolateProvider.startSymbol('<%');
    $interpolateProvider.endSymbol('%>');
})
.controller("index", ["$scope", function($scope) {
    $scope.$watch("value", function (newValue) {
        $scope.product = newValue.split("").reverse().join("");
    });
}]);

See it on Github