简体   繁体   中英

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";
        }
    });
});

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}}'
    };
  }
);

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!!!"
    }
  };
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM