The right paradigm for mixing angular code with external code

Angular Newbie here. I'm trying to understand the paradigm that should be used when developing an Angular application, so I can use external libraries while keeping the Angular application reusable.

So imagine I have a form that uses ng-submit:

 <form ng-submit="submit()">...<!--code goes here --></form> 

And then inside the respective ng-app and ng-controller (suppose they are declared in the parent), I have my submit function. But tell me, only on this page, I want to use a special warning library after sending:

 $scope.submit = function(){ // code goes here to submit form data //now tell the user that save was successful customAlertLibrary.alert("your data has been saved") } 

Now that the code is not being reused, is it? I can reuse this ng-app on another page to change and send data, but I do not want to use a special warning library. You seem to be trapped because the ng-submit attribute limits you to functions within the corresponding ng-app , not external functions. So, what is the correct way to invoke other Javascript code along with my Angular code without baking it into a model?

+5
source share
2 answers

This question is very similar to this question on how to make lodash available in templates . There are many ways to add external (or input) code or data structures to the Angular scope. I prefer to add special materials for each area separately and universal utilities (for example, lodash or momentjs) around the world :

 app .run(['$rootScope', function($rootScope) { $rootScope._ = _; $rootScope.moment= moment; // or: // $rootScope.util = { // _: _, // moment: moment // }; }); 
+1
source

If customAlertLibrary is not critical to your application, I would say something like this

 $scope.submit = function(){ // code goes here to submit form data //now tell the user that save was successful if ($window.customAlertLibrary) { customAlertLibrary.alert("your data has been saved"); } } 

Otherwise, I would suggest using Bower to manage dependencies. You install packages with Bower, and your own application may be the package that comes with the package and is installed by other applications. Any dependency of your application is also installed (the user should still include it at his end in the <script> )

0
source

Source: https://habr.com/ru/post/1211721/


All Articles