【发布时间】: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