Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
156 views
in Technique[技术] by (71.8m points)

javascript - Pass jQuery dependency to angular js controller

I am using angularjs 1.4, and in one of my angular controller I have to use jQuery. but when I am trying to pass it as dependency, it is not working.

I tried below code, but no success

(function () {
    'use strict';

    var app= angular.module('app');

    app.controller('getUserInfo', ['jQuery',
        function($) {
         // some logic
    }]);
})();

I also tried below code, but no success

(function () {
    'use strict';

    var app= angular.module('app');

    app.controller('getUserInfo', ['$',
        function($) {
         // some logic
    }]);
})();

Can some please guide what I am doing wrong.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could create your own constant inside your app module & then you can inject that dependency where ever you want.

app.constant('jQuery', window.jQuery)

I chosen constant, because It would be available to inject its dependency inside config phase of angular.

(function () {
    'use strict';

    var app= angular.module('app');

    app.controller('getUserInfo', ['jQuery',
        function($) {
         // $ will provide you all jQuery method available in it.
         //but don't do DOM manipulation from controller.
         //controller is not the correct place to play with DOM.
    }]);
})();

But as you wanted to inject dependency of jQuery inside a controller, I'd say NO. Don't do that. Basically you shouldn't do any DOM manipulation from the controller. You can do that from the directive, which has capability to playing in better way with DOM.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...