【问题标题】:jQuery Lite Element Finder with Ng-If on Angular DirectiveAngular 指令上带有 Ng-If 的 jQuery Lite 元素查找器
【发布时间】:2016-07-02 14:42:40
【问题描述】:

我有一个包含两个 html 元素的指令,一个是 ng-if 指令,另一个不是:

  <div>
     <div ng-if="true" id="ngIfTest">TEST WITH NG-IF</div>
  </div>

  <div>
     <div id="withoutNgIfTest">TEST WITHOUT NG-IF</div>
  </div>

我选择这样的元素:

var ngIfElement = angular.element(elem[0].querySelector('#ngIfTest'));
var noNgIfElement = angular.element(elem[0].querySelector('#withoutNgIfTest'));

我可以选择不使用 ng-if 的元素,但不能选择使用的元素。

LIVE EXAMPLE HERE (Click on the text to see it selecting one properly)

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

myApp.directive('myDirective', function() {
    return {
        link: function(scope,elem) {
        
        				//var myDivElement = elem #myDiv;
                var myDivElement = angular.element(elem[0].querySelector('.myDiv'));
        
                elem.bind('click', function() {
                    elem.css('background-color','red');
                    myDivElement.css('color','blue');
                    console.log('Element clicked');
                    scope.$apply(function() {
                        scope.color = "red";
                    });
                });
                
        }
    }
});


function MyCtrl($scope) {    
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-controller="MyCtrl">
    <div id="me" style= "background-color:yellow;" my-directive>
          <div id="myDiv" class="myDiv">TEST</div>
    </div>
</div>

我意识到这与 ng-if 创建自己的范围有关,但我不知道如何绕过它。

我从中提取的相关问题:AngularJS: How to .find using jqLite?

【问题讨论】:

  • 请注意,您的 jsFiddle(以及导入的 sn-p)不包含 ngIf 指令...
  • 看起来我没有保存更改。我稍后会更新。

标签: javascript jquery angularjs


【解决方案1】:

创建它自己的范围并不是真正的问题,这是因为ngIf 在条件不满足时不会写入 DOM,因此您的 jQuery 选择器永远不会找到它。如果您需要元素存在于 DOM 中并且可查询,请使用 ngShowngHide

【讨论】:

  • 看起来很合乎逻辑,赞成。过几天回来接受。
猜你喜欢
  • 2015-02-12
  • 1970-01-01
  • 2023-03-05
  • 2014-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-26
  • 1970-01-01
相关资源
最近更新 更多