javascript - 如何在指令之外调用方法?

标签 javascript angularjs directive

我是 Angular 使用指令的新手。有一个问题我需要帮助。 我有一个文件 common.js 。该文件内容方法:

function showAlert(value) {
   alert(value);
}

在指令中:

app.directive('ccDecimalinput', function($timeout, $parse){
      var FOCUS_CLASS = "error_tip error";
      var templateOut = '';
    //  console.log('ccDecimalinput ... ');
      return {
        restrict: 'E',
        require: 'ngModel',
        scope : {
            ngModel: '='
        },
        template: '<div ng-form="signup_form"><input type="text" class="maxlength_10_text left_aligned" id="' + attrs.id + '" name="' + attrs.name + '" ng-model="ngModel" required ng-minlength="1" ng-maxlength="10" /></div>'; ,
        replace : true,
        link: function(scope, ele, attrs, c) {
              scope.$watch('ngModel', function() {
                  if (scope.signup_form.$dirty && scope.signup_form.$invalid) {
                      //TODO
                      //I want to use method showAlert in common.js file here.
                      //....
                  }
              });
            }
        }
    });

有人帮帮我吗?

最佳答案

如果您已加载common.js脚本,您可以像平常一样调用该函数。它似乎是全局性的..

if (scope.signup_form.$dirty && scope.signup_form.$invalid) {
  showAlert('some value');
}

您可以像平常一样在 html 中加载脚本: <script src="path/to/common.js"></script>

另外,我希望这只是一个例子.. 包装 alert() 没有多大意义。通过它自己。您可以调用alert()直接使用,不需要外部函数。

关于javascript - 如何在指令之外调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20986098/

相关文章:

java - 小程序不适用于 chrome

javascript - JSON 对象的已知非空值的字段返回空字符串

html - 搜索栏标题

javascript - 多个 Controller 操纵 Angular 指令中的内容?

javascript - 在 MS Word 中使用 RegEx 匹配单词的变体和拼写错误

javascript - ChartJS 动态折线图在悬停时会重影回旧数据

angularjs - 如何使用 ui-router 检查身份验证并自动重定向到登录状态?

angularjs - mean.js 菜单 isPublic 不起作用

javascript - 在 AngularJS 中使用 templateURL 从外部资源加载

c++ - #ifndef#define 指令是什么意思