Javascript AngularJS如何编译指令?
我试图更好地理解AngularJS如何编译指令和更新视图 这是我的具体问题。我有这样的指示:Javascript AngularJS如何编译指令?,javascript,angularjs,Javascript,Angularjs,我试图更好地理解AngularJS如何编译指令和更新视图 这是我的具体问题。我有这样的指示: angular.module('directives', []) .directive('test', function() { return { restrict: 'AE', scope : { foo : '=' }, template: '<div id={{foo.id}}>{{foo.data}}</div>'
angular.module('directives', [])
.directive('test', function() {
return {
restrict: 'AE',
scope : { foo : '=' },
template: '<div id={{foo.id}}>{{foo.data}}</div>'
link: function(scope, element, attrs) {
document.getElementById(scope.foo.id); /*1*/
}
}
});
角度模块('指令',[])
.directive('test',function(){
返回{
限制:“AE”,
作用域:{foo:'='},
模板:“{foo.data}”
链接:函数(范围、元素、属性){
document.getElementById(scope.foo.id);/*1*/
}
}
});
在第1点定义了scope.foo.id
。但是,该指令的模板尚未编译,因此未设置div id,并且getElementById
返回null
。一旦页面完全呈现,并且我查看编译的模板,所有模板id都已成功设置为foo.id
我错过了什么
还需要注意的是,对于我的特殊情况,我需要通过它的id显式地与模板div
交互
编辑:添加了一个提琴:好的,鉴于有限的信息,我能够让元素为您工作。我不确定您想要做什么,但是您需要在指令中设置元素的id 如果有更好理解的人可以解释,我想知道为什么id没有绑定到模板中。如果您根据指令设置id,它似乎可以正常工作。() @Dan我还必须更改您的ID以使用前面的单词
test-
,因为HTML规范不允许ID以数值开头。根据规范:
ID和名称标记必须以字母([a-Za-z])开头,后面可以是任意数量的字母、数字([0-9])、连字符(“-”)、下划线(“)、冒号(:”)和句点(“.”)
var testApp=angular.module('testApp',[]);
testApp.controller('mainCtrl',['$scope',函数($scope){
$scope.bar=[
{id:1,msg:'这是一条很好的消息'},
{id:2,msg:'这条消息也很好'},
{id:3,msg:'还有一条消息'}
];
}]);
testApp.directive('plugin',function()){
返回{
限制:“EA”,
模板:“{foo.msg}}”,
作用域:{'foo':'='},
编译:函数编译(远程通讯、tAttrs、转置){
返回{
post:功能postLink(范围、元素、iAttrs、控制器){
element.attr('id','test-'+scope.foo.id);
log(document.getElementById('test-'+scope.foo.id));
/*这不提供空值*/
}
}
}
};
});
Question,它说你需要与模板交互,你想用模板做什么的详细信息?我正在尝试初始化元素上的插件,该插件明确需要将元素id传递给它。你能把它放在小提琴里吗?如果没有html和完整的js,你很难准确理解你在做什么。你能为我提供你插件的html吗?本质上,您所做的是使用element.html({{您的插件在这里运行}});然后执行$compile(element.contents())(scope);我现在正在处理一个fiddle。Foo是在控制器上定义的,我在指令的作用域上用scope:{Foo='='}
定义它。我只是想访问它,这样我就可以对元素进行一些DOM操作。难道你不能使用元素变量修改DOM吗?你有没有可能得到一个JSFIDLE来说明你想要什么?请参考我上面的评论。我需要id字符串,此时需要编译元素。请确保您了解指令的作用域设置。您需要了解何时将范围设置为false/true/或{}。请参阅答案中的链接。我正在明确尝试隔离范围。。。我不希望范围:false
var testApp = angular.module('testApp',[]);
testApp.controller('mainCtrl', ['$scope', function($scope) {
$scope.bar = [
{ id: 1, msg: 'this is a nice message'},
{ id: 2, msg: 'this message is also nice'},
{ id: 3, msg: 'yet another message'}
];
}]);
testApp.directive('plugin', function() {
return {
restrict : 'EA',
template: '<div>{{foo.msg}}</div>',
scope: {'foo': '='},
compile: function compile(tElement, tAttrs, transclude) {
return {
post: function postLink(scope, element, iAttrs, controller) {
element.attr('id', 'test-' + scope.foo.id);
console.log(document.getElementById('test-' + scope.foo.id));
/* This does not provide a null value */
}
}
}
};
});