AngularJS directives and isolate scopes

In this example below you will see how to do a AngularJS directives and isolate scopes with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by 01abhishekjain, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright 01abhishekjain ©

Technologies

  • HTML
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>AngularJS directives and isolate scopes</title>
  
  
  
  
  
</head>

<body>

  <body ng-app="app">

  <div ng-controller="divCtrl">
    a = {{a}}, obj = {{obj}}, b = {{b}}
    <br>1. iso-at directive:
    <iso-at a="{{a}}" x="obj" b="b" ext-logic="myLogic"></iso-at>
    <br><br> 2. transcluded directive
    <trans>Template passed in the directive's ng-transclude <i>slot</i> can access the directive's <b>parent's</b> scope: {{b}}</trans>

    <hr>

  </div>

</body>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.6/angular.js'></script>

  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/01abhishekjain/angularjs-directives-and-isolate-scopes-BJvWwe */
var app = angular.module("app", []);

app.controller("divCtrl", function($scope) {
  $scope.a = 1;
  $scope.obj = { k: 1 };
  $scope.b = 2;
  $scope.myLogic = function(a, b) {
    alert("sum is: " + (parseInt(a) + parseInt(b)));
  };
});

app.directive("isoAt", function() {
  return {
    restrict: "E",
    template: `a = {{a}}, x = {{x}}, b = {{b}}
<button ng-click="incA()">Inc a</button>
<button ng-click="incO()">Inc O()</button>
<button ng-click="incB()">Inc B()</button>
<button ng-click="extLogic()(a,b)">Execute parent's logic</button>
`,
    scope: {
      a: "@",
      x: "=",
      b: "=",
      extLogic: "&"
    },
    controller: function($scope, $elements, $attrs) {
      $scope.incA = function() {
        $scope.a++;
      };
      $scope.incO = function() {
        $scope.x.k++;
      };
      $scope.incB = function() {
        $scope.b++;
      };
    }
  };
});

app.directive("trans", function() {
  return {
    restrict: "E",
    scope: {},
    transclude: true,
    template: `<span>The next span will act as the slot since it has the ng-transclude attribute on it</span><br> <span ng-transclude><span>`
  };
});

Comments