将 jQuery 依赖项传递给 angular js 控制器 [英] Pass jQuery dependency to angular js controller

查看:30
本文介绍了将 jQuery 依赖项传递给 angular js 控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 angularjs 1.4,在我的一个 angular 控制器中,我必须使用 jQuery.但是当我尝试将其作为依赖项传递时,它不起作用.

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.

推荐答案

您可以在应用模块中创建自己的常量 &然后你可以在任何你想要的地方注入依赖.

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)

我选择了常量,因为它可以在 angular 的配置阶段注入它的依赖项.

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.
    }]);
})();

但是当您想在控制器中注入 jQuery 的依赖项时,我会说不.不要那样做.基本上你不应该从控制器做任何 DOM 操作.您可以从指令中做到这一点,该指令能够以更好的方式使用 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.

这篇关于将 jQuery 依赖项传递给 angular js 控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆