Angular: Directive

http://angularjs.org/

by miphe

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<div class="page" ng-app="myApp" ng-controller="MyCtrl">
    <form>
        <div class="form-group">
            <in></in>
            <p class="help-block">Write anything in the textarea, the result below should update.</p>
        </div>
        <button type="button" class="btn btn-primary" ng-click="resetModel()">
            Reset model to ---
        </button>
    </form>
    <hr />
    <h3>Result:</h3>
    <p id="result">-</p>
</div>

CSS

.page { padding: 3em; }
#result { background-color: #fdfeef; padding: 2em; border: 1px solid #ffeeaa; font-family: monospace; }

JavaScript

var myAppC = angular.module('myApp',['myApp.ctrl', 'myApp.directives']);
var myAppC = angular.module('myApp.ctrl',[]);
var myAppD = angular.module('myApp.directives',[]);

angular.module('myApp.ctrl')
    .controller('MyCtrl', function($scope) {
        console.log($scope.$id);
        
        // Resets the model to '---'
        $scope.resetModel = function() {
            $scope.target = '---';
        };
    
        // Applies a watcher to the model
        $scope.$watch('target', function(n, o) {
            $scope.reflectModel(n);
        });
    });

angular.module('myApp.directives')
    .directive('in', function() {
        return {
            restrict: 'E',
            template: '<textarea rows="3" class="form-control" ng-model="target"></textarea>',
            link: function(scope, element, attrs) {
                console.log(scope.$id);
                
                // Updates the DOM with new value
                scope.reflectModel = function(n) {
                    $('#result').text(n);
                };
            }
        };
    });