【问题标题】:How to pass directive scope value to a global javascript function called in template of the same directive?如何将指令范围值传递给在同一指令的模板中调用的全局 javascript 函数?
【发布时间】:2016-02-10 08:07:53
【问题描述】:

我有一个关于值在指令中的工作方式的问题。我有一个指令,它有一个模板,在同一个模板中,我想调用一个(全局定义的)javascript 函数,并且我想将我从 directive 获得的值传递到该 javascript 函数中(它可能听起来有点混乱)。 这是示例代码。

angular.module("Shell").directive("myFormField", function () {
return {
    scope: {
        text: "@",
        required: "@",
    },
    transclude: true,
    replace: true,
    template:
        '<div>' +
        '<label style="white-space: nowrap;font-weight: normal;width: 100% !important">'+globalLoadText(text)+
        '<div style="margin-top: 1.5px;" ng-transclude />' +
        '</label>' +
        '</div>'
};
});

globalLoadText() 是我在 angular 外部定义的全局方法(在根范围内的普通 js 文件中)text 将是我想从指令中获取的值。

我希望我已经清楚地写下了我的问题。任何帮助将不胜感激。谢谢!!

【问题讨论】:

  • 在我们赋予你做一些听起来很臭的事情之前,你能解释一下为什么你必须使用全局函数吗?
  • 为什么要尝试跳出 AngularJS 生态系统?如果你有一个全局函数,创建一个服务来在指令、控制器等之间共享函数。这样它是模块化的并且保持在 AngularJS 的摘要周期内。
  • 我认为问题是,您的函数将首先评估,而text 范围内不存在。使用过滤器而不是函数会起作用吗?所以你可以做{{text | globalLoadText}}docs.angularjs.org/api/ng/filter/filter

标签: javascript angularjs angularjs-directive angularjs-templates


【解决方案1】:

我强烈建议您解释为什么需要一个全局函数,因为它不难完成您想要的。但这并不意味着你应该这样做。

angular
  .module("Shell")
  .directive("myFormField", myFormFieldDirective);


myFormFieldController.$inject = ['$scope'];

function myFormFieldController($scope) {
  $scope.globalLoadText = _globalLoadText;

  function _globalLoadText() {
    return globalLoadText($scope.text);
  }
}


function myFormFieldDirective() {
  return {
    scope: {
      text: "@",
      required: "@",
    },
    transclude: true,
    replace: true,
    controller: myFormFieldController,
    template: '<div>' +
      '<label style="white-space: nowrap;font-weight: normal;width: 100% !important">{{globalLoadText()}}' +
      '<div style="margin-top: 1.5px;" ng-transclude />' +
      '</label>' +
      '</div>'
  };
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-09
    • 2013-04-20
    • 2017-03-10
    相关资源
    最近更新 更多