Friend
Friend

Reputation: 79

JavaScript directive not working like I would imagine it should

Link to Plunker.

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

  }])
  .directive('myCustomer', function() {
    return {
      restrict: 'E',
      scope: {
        customerInfo: '=info'
      },
      templateUrl: 'my-customer-iso.html',
      controller: 'testController'
    };
  });
})(window.angular);

I have values inside of Controller A (in the Plunker example, 'Controller') that I want to pass through to Controller B (in the Plunker example, 'testController') through the use of a Directive. Standard programming experience would have me thinking to do it as I have attempted to in the Plunker but when I look at the Run results I'm not getting the functionality I want.

What gives?

Upvotes: 0

Views: 48

Answers (2)

hayatoShingu
hayatoShingu

Reputation: 419

Link to plunker

You only miss to add $scope to customerInfo

 $scope.test.name = $scope.customerInfo.name;

Upvotes: 1

corn3lius
corn3lius

Reputation: 4985

the scope tag injects the object directly no need for a separate controller unless you need to have custom logic in the directive.

If it is just for display and structure this should start you off in the right direction.

(function(angular) {
  'use strict';
angular.module('docsIsolateScopeDirective', [])
  .controller('Controller', ['$scope', function($scope) {
    $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' };
    $scope.igor = { name: 'Igor', address: '123 Somewhere' };
  }])
  .directive('myCustomer', function() {
    return {
      restrict: 'E',
      scope: {
        customerInfo: '=info'
      },
      template: 'Name: {{customerInfo.name}} Address: {{customerInfo.address}}'
    };
  });
})(window.angular);


Name: {{customerInfo.name}} Address: {{customerInfo.address}}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>


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

Upvotes: 0

Related Questions