Angular Password Example

The following is a demo password generator app that showcases angular's rich declarative templates, data-binding, MVC, xhr service, and depenency injection.

HTML

<script type="text/javascript" ng:autobind
        src="http://code.angularjs.org/0.9.19/angular-0.9.19.js"></script>

<div ng:controller="PasswordController">
    Password:
    <input type="password" name="password" placeholder="enter password" />
    <span class="strength" ng:class="strength">This password is {{strength}} !</span><br />
 
    <input type="checkbox" name="showPwd"> Show password:
    <span ng:show="showPwd">{{password}}</span>
</div>

CSS

.strong   { background-color: #060; border-color: #0F0;}
.medium   { background-color: #C60; border-color: #FC0;}
.weak     { background-color: #900; border-color: #F00;}
.strength { padding: 1px 10px; border: 2px solid; color: #FFF;}

JavaScript

// url of the service
var SERVICE_URL = 'http://angularjs.org/generatePassword.php' + '?callback=JSON_CALLBACK';

// Dependency Injector injects $xhr service
function PasswordController() {

    // watch the password field and grade it.
    this.$watch('password', function() {
        if (angular.isDefined(this.password)) {
            if (this.password.length > 8) {
                this.strength = 'strong';
            } else if (this.password.length > 3) {
                this.strength = 'medium';
            } else {
                this.strength = 'weak';
            }
        }
    });

    // behavior
    this.generate = function() {
        var self = this;
        $xhr('JSON', SERVICE_URL, function(code, response) {
            self.password = response.password;
        });
    };
}