0

I have the example below.

HTML:

<body ng-controller="MainCtrl as MgtCtrl">
    <p>Hello {{MgtCtrl.name}}!</p>
    <p>Result is {{MgtCtrl.result}}!</p>
    <output-content data="MgtCtrl.name" result="MgtCtrl.result"></output-content>
</body>

JavaScript:

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

app.controller('MainCtrl', function($scope) {

  var MgtCtrl = this;

  MgtCtrl.name = 'World';
  MgtCtrl.result = "no";

  MgtCtrl.changeLabel = function() {
    alert('changeLabel');
    MgtCtrl.result = 'yes';
  }
});

app.directive('outputContent', function() {
  return {
    restrict: 'E',
    replace: true,
    templateUrl: 'outputContent.html',
    scope: {
      data: '=',
      changeLabel: '&',
      result: '='
    },
    controller: 'MainCtrl',
    controllerAs: 'MgtCtrl'
  };

});

ouputContent.html:

<div>
  {{data}}
  <button ng-click="MgtCtrl.changeLabel()">Change</button>
</div>

Plunker is: http://plnkr.co/edit/BW8VDyCaRnRgxE8I9JJy

I would like the result to be 'yes' when I click on the 'Change' button.

It doesn't work because of the named controller.

Could you please explain to me how to write the directive to do so ?

Regards.

2 Answers 2

2

You never was binding the scope variables to the named controller in the directive.

You must add the attribute bindToController: true to the directive definition like this plunker:

http://plnkr.co/edit/2QdnkpeuTM6adG9KoyJT?p=preview

Directive code:

app.directive('outputContent', function() {
  return {
    restrict: 'E',
    replace: true,
    templateUrl: 'outputContent.html',
    scope: {
      data: '=',
      changeLabel: '&',
      result: '='
    },
    controller: 'MainCtrl',
    controllerAs: 'MgtCtrl',
    bindToController: true
  };

});

This go to add the data and result binding to the respective directive controller.

Sign up to request clarification or add additional context in comments.

Comments

0

I think in this case you don't need to specify controller in the directive.

app.directive('outputContent', function() {
return {
    restrict: 'E',
    replace: true,
    templateUrl: 'outputContent.html',
    scope: {
      data: '=',
      changeLabel: '&',
      result: '='
    }
  };

});

Also html shoul be updated:

<body ng-controller="MainCtrl as MgtCtrl">
    <p>Hello {{MgtCtrl.name}}!</p>
    <p>Result is {{MgtCtrl.result}}!</p>
    <output-content data="MgtCtrl.name" result="MgtCtrl.result" change-label="MgtCtrl.changeLabel()"></output-content>
  </body>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.