Reputation: 33
How can I call a jQuery function or code with AngularJS?
For example, I have this HTML:
<iframe ng-src="{{v}}"></iframe>
And my controller:
angular.module("myApp", [])
.controller("AppCtrl", function($scope, myService) {
$scope.myScope = function() {
$('iframe').pluginCall();
myService.myFunc(function( data ){
$scope.myVar = 'Hey';
[...]
});
};
});
So, I want to run $('iframe').css('opacity','.5');
for the stuff that will be returned for me.
How can I do this?
Upvotes: 0
Views: 1018
Reputation: 171689
Use a directive to initialize jQuery plugins if you must use them. This assures you that element exists when plugin is initialized.
<iframe my-iframe>
JS
app.directive('myIframe', function(){
return{
link:function(scope, elem, attrs){
// elem is a jQuery object
elem.pluginCall();
}
}
});
Note that for angular to use jQuery internally for angular.element
, you must load jQuery.js
in page before angular.js
Upvotes: 1
Reputation: 6002
Never use jQuery
with angular unless & until required, because whatever is available in jquery is achievable in angularjs.
Dont Include ~18kb library into your page unnecessarily, for me its more like redundant code & also performance hit.
when coding a solution, first "think in AngularJS"; if you can't think of a solution, ask the community; if after all of that there is no easy solution, then feel free to reach for the jQuery. But don't let jQuery become a crutch or you'll never master AngularJS.
HTML CODE:
<div ng-app="testApp" ng-controller="testCtrllr">
<div ng-style="{'background-color': backgroundImageInfo}">
<input type="file" onchange="angular.element(this).scope().fileThatChangeBackground(this)" />
</div>
</div>
AngularJS Code:
angular.module('testApp',[])
.controller('testCtrllr', function($scope){
$scope.backgroundImageInfo='red';
$scope.fileThatChangeBackground = function(scope) {
$scope.$apply(function(){$scope.backgroundImageInfo='blue';});
};
});
Upvotes: 0
Reputation: 18933
You can use stuff like this :
$scope.yourAngularFunction=function(){
myService.myFunc(function( data ){
$scope.myVar = 'Hey';
$('iframe').css('opacity','.5');
$('#someOtherDiv').slideUp();
//add other jquery stuff
}
Upvotes: 0
Reputation: 3058
angular.module("myApp", [])
.controller("AppCtrl", function($scope, myService) {
$scope.myScope = function() {
$(function () {
// You can Write jquery here
$('iframe').css('opacity','.5');
});
myService.myFunc(function( data ){
$scope.myVar = 'Hey';
[...]
});
};
});
Upvotes: 0
Reputation: 13997
I don't think you should do that, use the angular way instead:
<iframe ng-src="{{v}}" ng-style="{ opacity: '.5' }"></iframe>
If you really want to get the object inside the controller, you can use angular's element queries:
angular.element(document.querySelector('iframe')).css('opacity','.5';
Upvotes: 1