0

I've just started using Angular.js and as I normally do, I quickly jumped to including jquery and a custom.js file where I have all the custom, small jquery snippets like on click events, etc.

Naturally, this didn't work.

Did some reading, turns out I have to use ng-click.

So, managed to get one snippet working by declaring this into my controller:

$scope.alert = function(text) {
    alert("YES!");
};

As you might imagine, not ideal.

Question is:

How can I have one custom.js file, or a service, or something, in which all the jquery snippets can be contained, and I can just call them with ng-click="alert" for example, or something like that.

I tried building a service for it, but I couldn't get it to work properly. The only service I built is also the only way I know to serve images in Angular, and that is:

'use strict';

//Image service
angular.module('mean.system').factory('ImageSol', [
    function() {
        return {
            logo : 'public/system/assets/img/logo-sol.png'
        };
    }
]);

To me it really seems excessive for just being able to serve a single image or a single jquery snippet.

user19882
  • 113
  • 7
  • Usually such scripts aren't needed when using angular... at most, you should have a set of custom directives as an independent module. You will have to review each snippet and evaluate if there's an already available directive to achieve the same result or if you need to write one. – rvignacio Jun 13 '14 at 15:40
  • 1
    I would give this question a good read first. http://stackoverflow.com/questions/14994391/how-do-i-think-in-angularjs-if-i-have-a-jquery-background?rq=1 – Mindstormy Jun 13 '14 at 15:41

1 Answers1

0

You cannot import all your jQuery plugin scripts and use them where ever you want (and if you can, don't!)

You have to build separate factories (or services, ..) for each plugin and use them by injecting in whatever controller you want.

And as you may have noticed, this is the main idea behind AngularJS, Dependency Injection!

For example, there is alert plugin in jQuery which recently I used alot in angular that works like this:

myApp.factory('AlertFac',function() {
    return {
        alertS:function(message) {
            alertify.set({
                delay : 5000
            });
        alertify.success("<span>"+message+"</span>");
        //return false;
    } }
});

This alertify function comes from a jQuery plugin which I inserted into my html in index, below the jQuery

So when ever I need to alert in my controller I do this :

myApp.controller('mainCtrl',function($scope,AlertFac){
     if(user clicked on a particular button){
         AlertFac.alertS('Hey buddy , whats up ?');
     }
})
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Milad
  • 27,506
  • 11
  • 76
  • 85