Angular: Learning new directives

Learning how to use the new scope qualifiers

by marco_m_alves

HTML

<script src="http://code.angularjs.org/1.0.0/angular-1.0.0.js"></script>
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script src="https://raw.github.com/documentcloud/underscore/master/underscore.js"></script>
<div ng-app="myApp" ng-controller="ListCtrl">
    {{master}} {{entry}}
    <br>
    <contact-editor entry="entry" on-input-change="onInputChange()"></contact-editor>
    <div ng-show='edited'>
        <br>
        <button class='btn btn-primary' ng-click='update()'>Update changes</button>
        <button class='btn' ng-click='cancel()'>Cancel changes</button>
    </div>
</div>

JavaScript

var myApp = angular.module('myApp',[]);

function Entry(obj){
    var that = {};
    
    _.extend(that, obj);

    that.clone = function(){
        return angular.copy(that);
    };

    that.update = function(data){
        _.extend(that, data);
    };
    
    return that;
}

myApp.directive('contactEditor', function(){
    return {
        restrict: "E",
        scope: {
            entry: "=",
            onInputChange: "&"
        },
        controller: function($scope){
            $scope.addTag = function(){
                $scope.entry.list.push($scope.tag);
                $scope.tag = "";
                $scope.onInputChange();
            }
        },
        template: '<input type="text" ng-model="entry.name" ng-change="onInputChange()"><br><form ng-submit="addTag()"><input type="text" ng-model="tag"></form>'
        
    };
});

myApp.controller('ListCtrl', function($scope){
    
    $scope.master = new Entry({ name: 'Marco' });
    
    $scope.master.list = [];
    
    $scope.entry = $scope.master.clone();
    
    $scope.edited = false;
    
    $scope.onInputChange = function(){
        console.log('controller on change');
        $scope.edited = true;
    };
    
    $scope.update = function(){
        $scope.master.update($scope.entry);
        $scope.edited = false;
    };
    
    $scope.cancel = function(){
        $scope.entry = $scope.master.clone();
        $scope.edited = false;
    };
});