Angular Scope Aliasing 3

by Tommy

HTML

<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>
  
  {{component}}
    
    <div ng-alias="{t: firstComponent()}" class="red-box">
      {{t.name}}
      <div ng-alias="{m: getChild(t)}" class="red-box">
        {{m.name}}
        <input type="text" ng-model="m.name"/>
        <div ng-alias="{b: getChild(m)}" class="red-box">
          {{b.name}}
          <input type="text" ng-model="b.name"/>
          
          <input type="text" ng-model="m.name"/>
        </div>
        {{b || '"b" not defined here'}}
      </div>
      {{m || '"m" not defined here'}}
    </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', '$parse',function($animate, $parse){
    
    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 data = $parse(expression)($scope);
          $transclude(function(clone, scope) {
            $animate.enter(clone, null, $element[0]);
            updateScope(scope, data);
          });  
        };
      }
    };
    
  }])
	.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;
    };
    
  }]);