Angularjs 排除:';元素';与templateUrl一起使用,是否可行?
我有一个指令,将元素放在一个隔离的范围内,并对其应用一个控制器,这样它就可以处理状态、AJAX调用和验证Angularjs 排除:';元素';与templateUrl一起使用,是否可行?,angularjs,angularjs-directive,Angularjs,Angularjs Directive,我有一个指令,将元素放在一个隔离的范围内,并对其应用一个控制器,这样它就可以处理状态、AJAX调用和验证 登录 当前被转移的元素变为: 登录 但是我有一个templateUrl,我想将它与指令的内容一起追加,所以我使用transclude:'element'来细化转换: angular .module('Login.module',[]) .controller('LoginCtrl',function(){ this.login=函数(){ //ajax是否需要登录 }; this.l
登录
当前被转移的元素变为:
登录
但是我有一个templateUrl
,我想将它与指令的内容一起追加,所以我使用transclude:'element'
来细化转换:
angular
.module('Login.module',[])
.controller('LoginCtrl',function(){
this.login=函数(){
//ajax是否需要登录
};
this.logout=函数(){
//ajax是否要求注销
};
this.facebook=function(){
//ajax调用facebook登录吗
};
this.showForm=函数(){
//显示模板表单
};
this.user={};//用户模型
})
.directive('login',function(){
返回{
限制:“A”,
转移:'元素',
controllerAs:'loginctrl',
控制器:“LoginCtrl”,
替换:false,
templateUrl:“/templates/login”,
链接:函数(范围、元素、属性、ctrl、transclude){
转移(范围、功能(克隆){
克隆。包裹(“”);
element.after(clone);/“element”是HTML注释
//“clone”是div的转置内容,即使用ng click等进行登录
});
}
}
});
templateUrl
(一种登录/注册表单)是通过AJAX下载的(请参见开发工具中的内容),但它不能在链接函数或transclude中使用。我错过什么了吗?在这方面找不到任何帮助,我已经找了几天了
问题的简化版本评论后编辑:
我更新了以下内容,我想这正是你想要的。我已经对发生的事情做了一些额外的解释
.directive('login', function() {
var useElementTransclusion = true;
var replace = true;
return {
restrict: 'A',
transclude: useElementTransclusion ? 'element' : true,
controllerAs: 'loginctrl',
controller: 'LoginCtrl',
replace: useElementTransclusion ? true : replace,
templateUrl: 'login.html',
link: function(scope, element, attrs, ctrl, transclude) {
// If transclude is 'element', then the element argument is
// the HTML comment which is put in the place of the entire
// element on which the directive was applied.
// If transclude is true, then the element argument depends
// on the value of replace. If replace is true then element
// is the content of the template. If replace is false then
// element is the element on which the directive was applied.
transclude(scope, function(clone) {
// If transclude is 'element' then clone is an array
// containing the single element on which the directive
// was applied.
// If transclude is true then clone is an array containng
// the children of the element on which the directive was
// applied.
element.wrap('<div class="login"></div>');
element.after(clone);
});
}
}
});
如图所示
这些变化是:
- 将替换更改为“true”
- 在包装之前将克隆添加到DOM中,以便包装也添加到DOM中
clone.wrap(…)
产生效果,则必须先执行元素。在(clone)
之后执行。
需要包装整个元素(模板+转置元素)。为什么它需要替换:true
?谢谢,它可以工作。有时,角度可能是一个黑匣子。这是一个令人惊讶的答案。帮了我很多忙。谢谢你的帮助@imaginaryboy
.directive('login', function() {
return {
restrict: 'A',
transclude: 'element',
controllerAs: 'loginctrl',
controller: 'LoginCtrl',
replace: true,
templateUrl: '/templates/login',
link: function(scope, element, attrs, ctrl, transclude) {
transclude(scope, function(clone) {
element.after(clone);
clone.wrap('<div class="login"></div>');
});
}
};
})