Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery function inside AngularJS controller

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
    });
});

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

like image 666
Adersh Avatar asked Sep 23 '26 20:09

Adersh


1 Answers

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

<div bootstrapswitch></div>

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>

...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();
      }
   };
}]);
like image 119
Sim Avatar answered Sep 26 '26 11:09

Sim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!