【发布时间】:2023-03-09 21:58:02
【问题描述】:
这可能是一个愚蠢的问题,但我已经坚持了好几天,谷歌搜索的解决方案都没有为我找到。
我正在按照指令驱动的方法编写一个 Angular 1.4 应用程序,因此对于任何实体我都有一个或多个小部件:
- 隔离范围
- 控制器为
- bindToController 为真
问题在于“用户有东西”的多样性。
<user-widget>
<stuff-widget userid="user._id"></stuff-widget>
</user-widget>
用户 ID 可以很好地传递到小部件中,但我想在东西小部件的链接函数中使用它,因为东西真的很复杂,在现实世界中我还需要获取其他各种部分。
我尝试了各种方法来获取 userid 值(如其他各种 stackoverflow 讨论和网络上的其他地方所建议的那样)
- 使用双向绑定 -> 无效
- 已通过范围和控制器尝试 -> 用户 ID,未定义 uid
- 需要 ^userWidget -> 无法访问我的控制器
- 使用 attrs.$observe('userid', ....) -> js 错误:未定义用户 ID
- 通过父级的预链接传递它 -> 确实有效,但不是一个好主意/有限的优点
我对我尝试过的各种事情都很感兴趣:http://plnkr.co/edit/SqlhYSteCDxMaAVZWCsy?p=info
小部件看起来像这样(工作前链接变体)
function userWidget() {
return {
restrict: 'EA',
scope:{},
template: '<h2>User</h2> {{user.name}}<stuff-widget userid="user._id"></stuff-widget>',
replace: false,
controllerAs: 'userCtrl',
bindToController: true,
controller: 'UserCtrl',
link: { // this actually works, not sure wether this a good idea
pre: function preLink(scope, element, attrs, ctrl) {
var uid = 1;
scope.user = ctrl.findById(uid);
scope.userid = scope.user._id;
},
post: function postLink(scope, element, attrs, ctrl) {}
}
};
}
function stuffWidget() {
return {
restrict: 'EA',
scope: {
uid: '=userid'
},
template: '<h3>User stuff</h3>stuffCtrl.userid inside widget: {{stuffCtrl.userid}}<div ng-repeat="stuff in stuffCtrl.userStuff">\
User id: {{stuff.userid}}: {{stuff.stuff}}\
</div>',
replace: false,
controller: 'StuffCtrl',
controllerAs: 'stuffCtrl',
bindToController: {
userid: '='
},
link: function (scope, element, attrs, ctrl) {
console.log('stuff ctrl userid:', ctrl.userid); // not defined
console.log('stuff scope uid:', scope.uid); // not defined
console.log('Scope parent userid: ',scope.$parent.userid); // undefined
// didn't work either - userid not defined
/* attrs.$observe('userid', function(value) {
if (value) {
ctrl.userid = userid;
console.log('stuff ctrl userid observed:', ctrl.userid);
}
}); */
ctrl.userStuff = ctrl.findByUserId(ctrl.userid);
}
};
}
我是 Angular 初学者(第一个认真的项目),到目前为止,我的经验是:“如果很难弄清楚,你可能做错了”。
所以,
- 我是否错过了访问链接函数中参数的明显方法?
- 我是否因为错误地将它们转移到我的设置而搞砸了我尝试过的方式(尤其是 $observe)?
- 我是否应该将控制器调用粘贴到模板中并完成它?
- 我应该采用完全不同的方式吗?编译功能?控制器功能?还有什么我不熟悉的角度深度?
【问题讨论】:
标签: javascript angularjs angularjs-directive