Thursday, May 21, 2015

AngularJS Directives - Isolated Scope

Here's an example for an Isolated Scope directive .  See the plunk here.  http://plnkr.co/lS8QIhaRbjqLlA7jHm2U

// Script.js
angular.module('app',[]);

angular.module('app').controller('mainCtrl', function($scope){
  $scope.user1 = {
    name: "Luke Skywalker",
    address: {
      street: '6332 Cameron Forest Ln',
      city: "Charlotte",
      planet: "Earth"
    },
    friends: ['Han', 'Leia', 'Chewbacca']
  };

    $scope.user2 = {
    name: "Mia Farrow",
    address: {
      street: '1236 Cameron Forest Ln',
      city: "Charlotte",
      planet: "Vulcan"
    },
    friends: ['Lan', 'Tia', 'Chewbacca']
  };

  //console.log('parent scope', $scope);
  //Take this in the directive, so we don't break encapsulation and the directive handles this event
  /*
  $scope.knightMe = function(user){
    user.rank = "knight";
  }
  */
});

/***************************************************************************/

//userCardInfo.html directive
angular.module('app').directive('userInfoCard', function(){
  return {
    restrict: "E",
    templateUrl : "userInfoCard.html",
    replace: true, // will replace directive with the contents and not display the directive tag in the html element as best practice
    //scope: true, //inherited scope; false = shared scope with parent containing controller is the default
                 //scope: {}, would be isolated scope and the directive cannot see the controller's scope now
    scope: {
        user :"="
      }, //isolated scope but now controller(parent) scope user object can be shared by passing in
         // an user object user1 from the controller. Useful as the same directive can now be used across multiple controllers
         // and they can pass in thier scope user objects.
    controller: function($scope){
        $scope.knightMe = function(user){
        user.rank = "Knight";
      }
    }
  }
})

/***************************************************************************/

//index.html
<!DOCTYPE html>
<html ng-app="app">

  <head>
      <script data-require="jquery@2.1.3" data-semver="2.1.4" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
    <link data-require="bootstrap@*" data-semver="3.3.2" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
    <script data-require="bootstrap@*" data-semver="3.3.2" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
    <script data-require="angular.js@1.3.0" data-semver="1.3.0" src="https://code.angularjs.org/1.3.0/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="mainCtrl" class="container">
    <h5>
       <user-info-card user="user1"></user-info-card>
       <user-info-card user="user2"></user-info-card>
    </h5>
 
  </body>

</html>

No comments:

Post a Comment