NewDeveloper NewDeveloper - 2 months ago 9
AngularJS Question

Angular directive access value in scope

How can I read a directive value like the info attribute in the scope?

<div ng-controller="Controller">
<my-customer info="naomi"></my-customer>
<hr>
<my-customer info="igor"></my-customer>
</div>


For example with this controller:

angular.module('docsIsolateScopeDirective', [])
.controller('Controller', ['$scope', function($scope) {
$scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' };
$scope.igor = { name: 'Igor', address: '123 Somewhere' };

//can I read the info value?
}])
.directive('myCustomer', function() {
return {
restrict: 'E',
scope: {
customerInfo: '=info'
},
templateUrl: 'my-customer-iso.html'
};
});


You can find it on plunker, or similar in the angular documentation.

Answer

Try this

Angular App

(function(angular) {
  'use strict';
angular.module('docsIsolateScopeDirective', [])
  .controller('Controller', ['$scope', '$attrs', function($scope, $attrs) {
    $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' };
    $scope.igor = { name: 'Igor', address: '123 Somewhere' };
    console.log($attrs.stars);
    console.log($attrs.info);
    //can I read the info value?
  }])
  .directive('myCustomer', function() {
    return {
      restrict: 'E',
      scope: {
            starts: '=stars',
            customerInfo: '=info'
      },
      controller: 'Controller',
      template: "Name: {{customerInfo.name}} Address: {{customerInfo.address}}"
    };
  });
})(window.angular);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-directive-isolate-production</title>
</head>
<body ng-app="docsIsolateScopeDirective">
  <div ng-controller="Controller">
  <my-customer info="naomi" stars="star1"></my-customer>
  <hr>
  <my-customer info="igor" stars="star2"></my-customer>
</div>
</body>
</html>

(function(angular) {
  'use strict';
angular.module('docsIsolateScopeDirective', [])
  .controller('Controller', ['$scope', '$attrs', function($scope, $attrs) {
    $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' };
    $scope.igor = { name: 'Igor', address: '123 Somewhere' };
    console.log($attrs.stars);
    console.log($attrs.info);
    //can I read the info value?
  }])
  .directive('myCustomer', function() {
    return {
      restrict: 'E',
      scope: {
            starts: '=stars',
            info: '=info'
      },
      controller: 'Controller',
      template: "Name: {{customerInfo.name}} Address: {{customerInfo.address}}"
    };
  });
})(window.angular);

Controller

<div ng-controller="Controller">
  <my-customer info="naomi" stars="star1"></my-customer>
  <hr>
  <my-customer info="igor" stars="star2"></my-customer>
</div>