StackOverflow_21220480: updating-scope-variable-from-directive

Illustration of answer to http://stackoverflow.com/questions/21220480/updating-scope-variable-from-directive.

by ExpertSystem

HTML

<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.angularjs.org/1.2.9/angular.min.js"></script>
<div ng-controller="myCtrl">
    <ul>
        <li><div class="well" demo-select>ABCD</div></li>
        <li><div class="alert alert-success" demo-select>CDEF</div></li>
        <li><input type="text"class="input-control" demo-select /></li>
        <li><button id="btn1" class="btn btn-success"
                    demo-select>Button</button></li>
    </ul>
    <pre>ID:    {{selected.id}}</pre>
    <pre>Class: {{selected.class}}</pre>
    <pre>Type:  {{selected.type}}</pre>
</div>

CSS

ul li {
    list-style: none;
}

.selected {
    border: 2px dashed #008000;
}

JavaScript

var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
    $scope.selected = {
        id:    'undefined',
        class: 'undefined',
        type:  'undefined'
    };
});

app.directive('demoSelect', function () {
    return {
        restrict: 'A',
        controller: 'myCtrl',
        link: function postLink(scope, elem, attrs, ctrl) {
            elem.on('click', function (evt) {
                evt.stopImmediatePropagation();
                evt.preventDefault();

                $('.selected').removeClass('selected');
                elem.addClass('selected');

                scope.$apply(function () {
                    scope.selected.id    = attrs.id;
                    scope.selected.class = attrs.class;
                    scope.selected.type  = elem.prop('tagName');
                });
            });
        }
    };
});