0

I'm trying to change the value of this.foo in my controller to "Bar" from my directive. This is my directive:

.directive('contenteditable', [
    function() {
      return {
        restrict: 'A', // only activate on element attribute
        require: '?ngModel', // get a hold of NgModelController
        controller: SearchCtrl,
        link: function(scope, element, attrs, ngModel) {
            scope.foo = "Bar";
        }
      };
    }
]);

This is my controller:

function SearchCtrl() {
     this.foo = "hello";
}

I'm removing a lot of code for simplicity, but the directive and the controller are linked up properly and to the same module.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Hackerman
  • 1,289
  • 1
  • 14
  • 29
  • 1
    Linking a scope with a controller is typically accomplished by setting the `bindToController` property. However, your example directive doesn't appear to be designating a child or isolate scope, which is expected if you want to set variables on the directive scope and access them in the corresponding controller. How is `SearchCtrl` and `contenteditable` defined in your HTML? – miqh Apr 19 '19 at 08:28
  • I'm using contenteditable for table cells (td tags) for its regular use case (See: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/contenteditable.). SearchCtrl is defined as
    enveloping everything in body
    – Hackerman Apr 19 '19 at 12:41
  • The sequencing of the life-cycle of a directive controller and the directive linking function can be a bit tricky. It is best to minimize the [coupling](https://en.wikipedia.org/wiki/Coupling_(computer_science)) between the two. – georgeawg Apr 19 '19 at 14:46
  • Instantiating the same controller with the `ng-controller` directive and with a custom directive on the same element is not wise. Also if the `ng-controller` directive is used without the "controller as" syntax. The is no point to using the `this` context in the controller. – georgeawg Apr 19 '19 at 14:52
  • Look at the `contenteditable` directive example in the [AngularJS Developer Guide - Implementing custom form controls (using `ngModel`)](https://docs.angularjs.org/guide/forms#implementing-custom-form-controls-using-ngmodel-). – georgeawg Apr 19 '19 at 14:58

0 Answers0