AngularJS explicit scope with attributes

by dekkard

HTML

<div ng-app="helloHabrahabr">
    <div ng-controller="forExampleController">
        <div habra-habr1="attr_as_string" some-attr="Hello1 Habr! attr"></div>    
        
        <div habra-habr2="attr_as_var_name" some-attr="scopedVar"></div>
        
        <div habra-habr3="attr_as_expression" some-attr="a+b"></div>
    </div>
</div>

JavaScript

function forExampleController($scope){
    $scope.scopedVar = "How are you?";

}

angular.module('helloHabrahabr', [])
    .directive('habraHabr1', function() {        
        return {
            template:"habraHabr1: '{{hello}}'",
            scope: {
                /* Префикс "@" означает, что локальной переменной будет присвоено значение атрибута
                */
                hello: '@someAttr'
            }
        }
    })

    .directive('habraHabr2', function() {        
        return {
            template:"habraHabr2: <input ng-model='hello2'>, interpolated: {{hello2}}",
            scope: {
                /* Префикс "=" означает, что в атрибуте передается уже не строчка, а имя некоторой переменной в текущем Scope
                */
                hello2: '=someAttr'
            }
        }
    })

    .directive('habraHabr3', function() {        
        return {
            template:"habraHabr3: interpolated: {{ helloFunc({a:3,b:5}) }}",
            scope: {
                /* "&" предполагает, что атрибут содержит некое выражение. К примеру, «c= a+b» или проще «a+b». И теперь ваша локальная переменная становится функцией, в которую можно передавать параметры. Параметры передаются в объекте, ключами которого выступают имена переменных в функции.
                */
                helloFunc: '&someAttr'
            }
        }
    })
;