Saqib Ali
Saqib Ali

Reputation: 12585

How can I get pass value from controller back to directive's template attribute in AngularJS?

I have created an AngularJS directive as shown below. In the associated controller, I compute the value of a variable text as "SomeText". I want this text to replace Hello World!! in the template attribute of the directive. How can I do it?

My HTML:

<myp-directive myarg="myObject"></myp-directive>

My Directive:

myApp.directive('mypDirective',function(){
    return {
      restrict:'E',
      scope: {
        myarg: '='
      },
      controller: 'DirectiveCtrl',
      controllerAs: 'directiveCtrl',
      bindToController: true,
      template: 'Hello World!!'
    };
  }
);

My Controller:

myApp.controller('DirectiveCtrl', function($scope){
    var self = this;
    $scope.$watch(function() {return self.prediction;}, function (newVal, oldVal)
    {
        if (newVal !== oldVal && newVal !== null){
          var text = "SomeText";
        }
    });
});

Upvotes: 3

Views: 83

Answers (2)

Christiaan
Christiaan

Reputation: 848

Since you use the controllerAs: 'directiveCtrl' configuration you can simply assign "SomeText" as a variable of the controller (self) and it will be available in the template.

Pascal Precht wrote quite an extensive explanation about controllerAs.

Controller

myApp.controller('DirectiveCtrl', function($scope){
    var self = this;
    self.text = "Hello World!!";
    $scope.$watch(function() {return self.prediction;}, function (newVal, oldVal)
    {
        if (newVal !== oldVal && newVal !== null){
          self.text = "SomeText";
        }
    });
});

Directive

myApp.directive('mypDirective',function(){
    return {
      restrict:'E',
      scope: {
        myarg: '='
      },
      controller: 'DirectiveCtrl',
      controllerAs: 'directiveCtrl',
      bindToController: true,
      template: '{{directiveCtrl.text}}'
    };
  }
);

Upvotes: 4

Pratik Bhattacharya
Pratik Bhattacharya

Reputation: 3746

Use scope. Bind the text 'Hello World' to a scope variable (data) and bind it in the template as {{data}}. The change the value of the scope variable from the controller.

Take a look at this fiddle

Directive

myApp.directive('mypDirective', function() {
  return {
    restrict: 'E',
    scope: {
      myarg: '='
    },
    controller: 'DirectiveCtrl',
    controllerAs: 'directiveCtrl',
    bindToController: true,
    template: '{{data}}',
    link: function(scope, elem, attr, directiveCtrl) {
      scope.data = "Hello World!!!"
    }
  };
});

Upvotes: 3

Related Questions