Angular Scope Aliasing 2
by Tommy
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-sanitize/1.4.8/angular-sanitize.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.js"></script>
<div ng-app="app" ng-controller="ctrl" class="blue-box">
<input type="text" ng-model="world" />
<br/>
<input type="text" ng-model="obj.name" />
<br/>
<br/>
Hello {{world}}
<br/>
<div ng-alias="{a: world, b: 'hello', o: obj, name: obj.name, n: obj.name}" class="red-box">
{{b}} {{a}} {{world}}
{{helper(1)}}
<br/>
{{o.name}}
<input type="text" ng-model="o.name"/>
<br/>
{{name}}
<br/>
{{n}}
</div>
<div ng-alias="{t: firstComponent()}" class="red-box">
{{t.name}}
<div ng-alias="{m: getChild(t)}" class="red-box">
{{m.name}}
<div ng-alias="{b: getChild(m)}" class="red-box">
{{b.name}}
</div>
</div>
</div>
<br/>
{{a || 'What is "a"?' }}
<br/>
{{b || 'What is "b"?' }}
<br/>
{{o || 'What is "o"?' }}
<br/>
{{name || 'What is "name"?' }}
<br/>
{{n || 'What is "n"?' }}
</div>
CSS
.blue-box {
border: 1px blue solid;
padding:5px;
margin:5px;
}
.red-box {
border: 1px red solid;
padding:5px;
margin:5px;
}
JavaScript
angular.module('app',[])
.directive('ngAlias',['$animate',function($animate){
return {
restrict: 'A',
multiElement: true,
transclude: 'element',
priority: 1000,
terminal: true,
$$tlb: true,
compile: function ngRepeatCompile($element, $attr) {
var expression = $attr.ngAlias;
function updateScope(scope, data){
_.extend(scope,data);
}
return function link($scope, $element, $attr, ctrl, $transclude) {
var block = {};
$scope.$watch(expression, function(newValue, oldValue) {
if(!block.scope){
$transclude(function(clone, scope) {
block.scope = scope;
$animate.enter(clone, null, $element[0]);
updateScope(block.scope, newValue);
});
} else if(!angular.equals(newValue, oldValue)) {
updateScope(block.scope, newValue);
}
});
};
}
};
}])
.controller('ctrl',[
'$scope',
function($scope){
$scope.world = 'World!';
$scope.obj = {
name: 'Tom'
};
$scope.component = {
name: 'top',
child: {
name: 'middle',
child: {
name:'bottom'
}
}
};
$scope.helper = function(num){
return num * 100;
};
$scope.getChild = function(c){
return c.child;
};
$scope.firstComponent = function(){
return $scope.component;
};
}]);