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

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

问题描述

我正在使用angularjs 1.4,在我的一个角度控制器中,我必须使用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.

推荐答案

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

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天全站免登陆