Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct paradigm for mixing angular code with external code

Angular Newbie here. I'm trying to understand the paradigm to use when developing an Angular app so I can use external libraries while keeping the Angular app reusable.

So imagine I've got a form that uses ng-submit:

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

And then inside the corresponding ng-app and ng-controller (assume those are declared in a parent element), I've got my submit function. But say, on this page only, I want to use a custom alert library after submitting:

$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's not reusable code, is it? I may want to reuse this ng-app on another page to modify and submit data, but don't want to use the custom alert library. It seems like you're trapped because the ng-submit attribute restricts you to functions inside the corresponding ng-app, not external functions. So what is the correct way to invoke other Javascript code alongside my Angular code without baking it into the model?

like image 757
J-bob Avatar asked Nov 10 '22 20:11

J-bob


1 Answers

This question is very similar to this question about making lodash available in templates. There are many ways of adding external (or in-app) code or data-structures to your Angular scope. I prefer to add special-purpose stuff to each scope individually, and general-purpose utilities (such as lodash or momentjs) globally:

app
.run(['$rootScope', function($rootScope) {
    $rootScope._ = _;
    $rootScope.moment= moment;

    // or:
    // $rootScope.util = {
    //      _: _,
    //      moment: moment
    // };
});
like image 108
Domi Avatar answered Nov 14 '22 23:11

Domi