【问题标题】:Access jquery object from angular functions从角度函数访问 jquery 对象
【发布时间】:2015-01-10 01:22:05
【问题描述】:

我有一个带有 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 就好了。但是当角度函数 $scope.myFunction 运行时,角度会抛出错误“myGadget is not defined”。我明白为什么 - 它正在寻找角度变量,而不是 jquery 变量。那么如何在角度函数中访问 jquery 变量 myGadget 呢?

【问题讨论】:

    标签: jquery angularjs


    【解决方案1】:

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

    //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
    
    }
    

    【讨论】:

    • 这已经足够接近了,因为“myGadget 不在范围内”是关键问题。但是,使用var 不起作用,但使用 $scope 可以:) 因此,如果您可以将var myGadget 更改为$scope.myGadget,我将奖励您。确保在任何地方都使用$scope.myGadget
    【解决方案2】:

    您正在私有范围内创建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();
    }
    

    顺便说一句 angular.element === jQuery 以防 jQuery 与 Angular 一起使用

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

    【讨论】:

    • 我不能使用 angular.element 因为它默认为 jQlite。
    • 这是错误的,如果你删除var $jq = jQuery.noConflict() angular.element 将等于jQuery。
    猜你喜欢
    • 2017-06-27
    • 1970-01-01
    • 2022-01-16
    • 2018-09-13
    • 2014-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多