在AngularJS控制器中使用jQuery函数 [英] Using jQuery function inside AngularJS controller

查看:53
本文介绍了在AngularJS控制器中使用jQuery函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在所有带有某个类名的元素上初始化一个 jQuery 插件,该类名在 ng-repeat 循环。这些元素通过 angularjs $ http get 方法加载。

I needed to initialize a jQuery plugin on all elements with a certain class name which comes inside an ng-repeat loop. These elements are loaded via angularjs $http get method.

var app = angular.module('myApp', []);

app.controller('myController', function($scope, $http) {
    $http.get('get_item.php').success(function(response) {
        $scope.items = response;
        angular.element('.make-switch').bootstrapSwitch(); // jQuery plugin code
    });
});

但这不起作用。
我试过 $('。make-switch')。bootstrapSwitch(); 也。请帮忙。

But this doesn't work. I tried $('.make-switch').bootstrapSwitch(); also. Please help.

推荐答案

创建一个指令,这样你就可以在你的标记中初始化插件:

Create a directive and so you can initialize the plugin in your markup:

<div bootstrapswitch></div>

我认为您使用范围变量动态创建元素 $ scope.items ,类似:

I think you creates your elements dynamicly with the scope variable $scope.items, something like that:

<div class="make-switch" ng-repeat="item in items" bootstrapswitch></div>

...只需添加属性 bootstrapswitch 初始化已加载元素的开关。

...just add the attribute bootstrapswitch to initialize the switch on your loaded elements.

...您的指令可能如下所示:

...your directive could look like that:

app.directive('bootstrapswitch', [function() {
   return {
      restrict: 'A',
      link: function(scope, elem, attrs) {
         $(elem).bootstrapSwitch();
      }
   };
}]);

这篇关于在AngularJS控制器中使用jQuery函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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