Isolated Scope Example

This is the Example for the Isolated Scope

by DineshAngappa

HTML

<div ng-app="myModule">
  <div ng-controller="customerCtrl">
      <h3> Isolated Scope with Name </h3>
    <div my-directive-with-name name="{{customer.name}}"></div>
      <br/>
      <h3> Isolated Scope with Model </h3>
      <div my-directive-with-model customer="customer"></div>
      <br/>
      <h3> Isolated Scope with Model and Function </h3>
      <div my-directive-with-model-and-function datasource="customer"
          action="changeData()"
      ></div>
  </div>
</div>

JavaScript

var app = angular.module('myModule', []);

app.controller("customerCtrl", ['$scope',function ($scope) {
     var counter = 0;
    
    $scope.customer = {
        name: 'John',
        address: 'st.thomas street'
    };
    
    $scope.customers = [
        {
            name: 'John',
            address: 'St.thomas street'
        },
        {
            name: 'Sam',
            address: 'Churchill.'
        },
        {
            name: 'Michelle',
            street: 'Lake front'
        }
    ];
    
    $scope.addCustomer = function () {
        counter++;
        $scope.customers.push({
            name: 'New Customer' + counter,
            address: counter + ' Point St.'
        });
    };
    
     $scope.changeData = function () {
        counter++;
        $scope.customer = {
            name: 'James',
            address: counter + ' Point St.'
        };
    };
    
}]);

app.directive("myDirectiveWithName", function () {
  return {
    scope: {
     name : "@"
    },
    template: 'Name: {{name}}'
  };
});

app.directive("myDirectiveWithModel", function () {
  return {
    scope: {
     customer : "="
    },
    template: '<ul><li ng-repeat="prop in customer">{{ prop }}</li></ul>'
  };
});

app.directive("myDirectiveWithModelAndFunction", function () {
  return {
    scope: {
     	datasource : "=",
        action: '&'
    },
    template: '<ul><li ng-repeat="prop in datasource">{{ prop }}</li></ul> ' +
                  '<button ng-click="action()">Change Data</button>'
  };
});