javascript - 在 AngularJS 中,如何将 Controller 的传递值返回到指令的模板属性?

标签 javascript angularjs

我创建了一个 AngularJS 指令,如下所示。 在关联的 Controller 中,我将变量 text 的值计算为 "SomeText"。我希望此文本替换指令的 template 属性中的 Hello World!!。我该怎么做?

我的 HTML:

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

我的指令:

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

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

最佳答案

由于您使用了 controllerAs: 'directiveCtrl' 配置,您可以简单地将 "SomeText" 指定为 Controller (self)的变量,它将在模板。

Pascal Precht 写了相当广泛的 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";
        }
    });
});

指令

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

关于javascript - 在 AngularJS 中,如何将 Controller 的传递值返回到指令的模板属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37067401/

相关文章:

javascript - 如何在 AngularJS 的任何 View 中刷新或重新加载后加载主页?

javascript - 通过将 var 传递给函数来隐藏 Div

javascript - Angular Js ng-repeat 遍历 JSON

javascript - 拟合时的 TensorflowJS,损失为 NaN

javascript - IE 中的 AngularJS 错误与风格 vs ng 风格

javascript - Angular,用 settimeout 模拟 promise ($q)

javascript - 调试 jQuery AJAX 响应 : what I'm doing wrong?

javascript - 预加载Javascript音频以在脚本中播放

javascript - 如何删除index.html和karma中加载的脚本文件中的重复项?

javascript - 如何模拟 `angular.element`