1

我对值在指令中的工作方式有疑问。我有一个指令,它有一个模板,在同一个模板中我想调用一个(全局定义的)javascript 函数,我想将我从指令中获得的值传递到该 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 文件中)文本将是我想从指令中获取的值。

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

4

1 回答 1

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>'
  };
}
于 2016-02-10T00:05:38.980 回答