在模板范围内访问DOM——AngularJS
Accessing DOM within template scope - AngularJS
我对Angular JS很陌生,我处于一种情况,我需要在我的指令模板中选择一些DOM元素(我知道DOM操作在Angular中是不受欢迎的,但在我的情况下,如果没有大量的时间投入,我真的看不到太多的方法……)。问题是我不止一次地使用了我的指令。
下面是一个代码示例来澄清我的意思:
我的index . html。
<html>
<head> <! necessary script> </head>
<body ng-app='foo'>
<my-directive my-attr="someVal"></my-directive>
<my-directive my-attr="otherVal"></my-directive>
</body>
</html>
我的JS:
angular.module('foo',[]).directive('myDirective', function() {
return {
restrict: 'E',
templateUrl: 'foo-template.html',
scope: {},
replace: true,
link: function(scope,elem,attrs) {
//jQuery selector
scope.bar = angular.element($('.bar').first());
scope.bar.someFunction(attrs.myAttr);
function someFunction(message) {
scope.bar.html(message);
}
}
};
});
My template (foo-template.html):
<p class='bar'></p>
注入后,我的index。html看起来像这样:
<html>
<body>
<p class='bar'>otherVal</p>
<p class='bar'></p>
</body>
</html>
当我希望它是:
<html>
<body>
<p class='bar'>someVal</p>
<p class='bar'>otherVal</p>
</body>
</html>
我想限制我对当前被控制的模板内的访问,因为我第二次使用我的指令,它达到第一段并更新它。我认为使用隔离作用域可以解决这个问题,但是它没有。
有谁知道如何实现这一点(或有任何提示如何重构我的代码,使我不必选择DOM元素)?非常感谢!
你已经有了指令链接函数中指定的每个元素的引用:
angular.module('foo',[]).directive('myDirective', function() {
return {
restrict: 'E',
templateUrl: 'foo-template.html',
replace: true,
link: function(elem, attrs) {
elem.html(attrs.myAttr);
}
};
});
元素引用已经包含在angular.element
中,因此您应该能够在其上使用这些函数。如果需要直接的DOM引用,请使用elem[0]
。
除非你的例子比你正在做的任何事情都简单,否则我认为你只是以错误的方式接近它。您也可以简单地这样做:
模板:
<p class='bar'>{{message}}</p>
JS:
link: function(scope,elem,attrs) {
scope.message = attrs.myAttr;
}
相关文章:
- 从angularjs中的javascript更新dom
- AngularJS Navigation (li ng-repeat, create header li), DOM
- Ionic:AngularJS变量未使用$scope更新DOM
- angularjs-bindng-click从jquery动态加载DOM
- AngularJS操作父'指令中的DOM
- AngularJS:当过滤值发生变化时刷新DOM
- AngularJS-独立的控制器和DOM操作
- AngularJS:在使用嵌套的JQuery Sortables时保持Dom和Model同步
- 如何在具有相同DOM结构的AngularJS中转换$(#someid)
- AngularJS,引用指令中的其他DOM项
- 使用AngularJS在Bootstrap选项卡之间移动DOM元素
- AngularJS在HTML渲染后使用JQuery操作DOM
- AngularJS-$scope不绑定到DOM
- AngularJS完成异步加载后将内容添加到DOM
- AngularJS:在长时间循环期间强制更新DOM(即进度指示器)
- angularjs 子指令 DOM 加载速度不够快
- 如何使用 AngularJS 从 DOM 元素的值创建一个数组
- AngularJS :如何创建DOM并绑定到基于任意分层数据的模型
- 在模板范围内访问DOM——AngularJS
- 在DOM - AngularJS中等待指令完成加载