从角度函数访问jquery对象

时间:2015-01-09 15:42:29

标签: jquery angularjs

我有一个带有angularjs和jquery的应用程序。我在以下angularjs脚本中有一些jquery:

//allow co-existence of jquery and angular 
var $jq = jQuery.noConflict();
//initialize an angular scoped variable taht will be manipulated and used by jquery object
$scope.myOption1 = true;

//jquery ready function
$jq(function() {
   var myGadget = $jq('.gadget-container').gadget({ 
     option1:  $scope.myOption1
   });
});


//angular function to manipulate the jquery object (which represents an image slider)
$scope.myFunction = function() {
  //change myOption1 to false
  $scope.myOption1 = false;

  //re-initialize myGadget with new myOption1 value
  myGadget.reInit();    //reInit is a built-in function for myGadget to reinitialize the gadget when options change

}

Jquery可以访问$ scope.myOpyion1就好了。但是当angular函数$ scope.myFunction运行时,angular会抛出错误“myGadget is not defined”。我理解为什么 - 它正在寻找角度变量,而不是jquery变量。那么如何在角度函数中访问jquery变量myGadget?

2 个答案:

答案 0 :(得分:2)

myGadget不在范围内。在myGadget关闭之外声明ready

//allow co-existence of jquery and angular 
var $jq = jQuery.noConflict();
//initialize an angular scoped variable taht will be manipulated and used by jquery object
$scope.myOption1 = true;

$scope.myGadget = null;

//jquery ready function
$jq(function() {
   $scope.myGadget = $jq('.gadget-container').gadget({ 
     option1:  $scope.myOption1
   });
});


//angular function to manipulate the jquery object (which represents an image slider)
$scope.myFunction = function() {
  //change myOption1 to false
  $scope.myOption1 = false;

  //re-initialize myGadget with new myOption1 value
  $scope.myGadget.reInit();    //reInit is a built-in function for myGadget to reinitialize the gadget when options change

}

答案 1 :(得分:0)

您正在私有范围内创建myGadget

虽然有很多需要改进的地方,但请尝试

var myGadget;

//jquery ready function
$(function() {
   myGadget = $('.gadget-container').gadget({ 
     option1:  $scope.myOption1
   });
});


//angular function to manipulate the jquery object (which represents an image slider)
$scope.myFunction = function() {
  //...

  myGadget.reInit();
}

BTW angular.element === jQuery以防jQuery与Angular一起使用

并且不需要使用$jqnoConflict,因为角度不会覆盖$符号