2014-02-27 66 views
3

我在app.js的標準功能定義如下:如何從AngularJS控制器調用自定義Javascript函數?

var app = angular.module('app', ['ngResource', 'ngRoute', 'ngSanitize'], function() { 

}); 


$(document).ready(function() { 
    // standard error box 
    function showError(title, content) { 
     $.bigBox({ 
      title: title, 
      content: content == null ? "An error occurred.<br /><br />If this error persists, please contact support." : content, 
      color: "#C46A69", 
      //timeout: 6000, 
      icon: "fa fa-warning shake animated", 
      //number: "1", 
      timeout: 3000 
     }); 
    } 
}); 

在AngularJS控制器的方法,我想能夠調用showError():

    someFunction() 
         .success(function (result) { 
          // great! 
         }) 
         .error(function (error) { 
          // call standard error message function 
          showError("Update Failed"); // use default error message 
         }); 

我知道app.js是加載,但我不確定如何在AngularJS的上下文中調用我自己的一些自定義函數。

有一個在angular.module定義中的殘留功能,因爲我試圖把我的自定義功能,在那裏,看看是否這會工作 - 沒有。

什麼是解決這個問題的適當方法?

- 更新 -

爲了澄清,我將要調用像許多控制器showError()showSuccess()許多自定義功能,使這些功能應該具有全局範圍,而不是侷限在一個特定的角度控制器。

+0

你就不能從'document.ready'刪除,並在全球範圍內定義它們? – Danny

回答

3

好,只需從任何地方調用它,因爲它的JavaScript,但你永遠不應該使用全局的功能,所以我將創建一個我需要的功能警報服務,然後通過注射它的控制器內部使用它。

angular.module('yourModule').factory('alertService', function() { 
    return { 
     showError : function() { 
      $.bigBox({ 
       title: title, 
       content: content == null ? "An error occurred.<br /><br />If this error persists, please contact support." : content, 
       color: "#C46A69", 
       //timeout: 6000, 
       icon: "fa fa-warning shake animated", 
       //number: "1", 
       timeout: 3000 
      }); 
     } 
    }; 
}); 

然後你可以注入任何控制器內,並使用它:

angular.module('yourModule').controller('yourController', function($scope, alertService) { 
    someFunction().success(function (result) { 
     // great! 
    }).error(function (error) { 
     // call standard error message function 
     alertService.showError("Update Failed"); // use default error message 
    }); 
}); 

然後,您可以添加更多的功能,像showSuccess服務,它有需要在短短一個地方的變化的優勢如果您決定將來有一段時間將該插件替換爲另一個插件或對該服務進行任何更改。

警告

創建指令任何jQuery插件整合的情況下,99%的路要走。我相信一個簡單的alertService可以在這種情況下「彎曲」規則,以避免在指令中廣播和捕獲事件而導致過度複雜化。

+0

你爲什麼要在服務中引發jQuery插件?任何DOM操作都應該在指令中。 –

+0

因爲它是就會立刻發出警告插件的類型,它不需要綁定到現有的HTML元素,因此我不認爲將其綁定到模板需要 –

+0

它仍然DOM操作,因此,需要將在指令。 –

相關問題