0

Below is the code illustrating the isolated scope scenario.

directivesModule.controller('CustomersController', ['$scope', function ($scope) {

    var counter = 0;
        $scope.customer = {
        name: 'David',
        street: '1234 Anywhere St.'
        };
}]);

directivesModule.directive('myIsolatedScopeWithName', function () {
return {
    scope: {
        name: '@',
    },
    template: 'Name: {{ name }}'
    };
});

We can add below code in HTML to access the customer.name in isolated scope in directive

<div my-isolated-scope-with-name name="{{ customer.name }}"></div>

Now the question here is if we need multiple objects of controller to be accessed in isolated scope. Do we need to mention all of them in HTML or is there a way that we can access them directly in JS.?

sandiee
  • 153
  • 1
  • 8

2 Answers2

0

You can pass whole outer $scope to isolated scope of directive:

angular.module('app', []).controller('ctrl', function($scope) {
$scope.obj1 = {
  name: 'Tom'
};
$scope.obj2 = {
  amount: 30
};
}).directive('test', function() {
  return {
    scope: {
      parent: '=',
    },
    template: 'Name: {{parent.obj1.name}}, Amount: {{parent.obj2.amount}}'
  };
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>

<div ng-app='app' ng-controller='ctrl'>
  <div test parent='this'></div>
</div>

You also can refuse from isolated scope(not declare it at directive):

angular.module('app', []).controller('ctrl', function($scope) {
  $scope.obj1 = {
    name: 'Tom'
  };
  $scope.obj2 = {
    amount: 30
  };
}).directive('test', function() {
  return {
    template: 'Name: {{obj1.name}}, Amount: {{obj2.amount}}'
  };
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>

<div ng-app='app' ng-controller='ctrl'>
  <div test></div>
</div>
Slava Utesinov
  • 13,410
  • 2
  • 19
  • 26
0

If you are using angular JS version 1.3 and above, there is a property called "bindToController" which you can set to true in your directive. This will make all isolated scope objects/variables defined, accessible the directive controller.

directivesModule.directive('myIsolatedScopeWithName', function () { return {
scope: {
    name: '@'
},
template: 'Name: {{ name }}',
bindToController: true };});

then in the controller you can access the isolated scope variable "name" using:

$scope.name

Please let me know if this is what you were looking for.