[英]angularjs directive use parameter inside link function
這可能是一個愚蠢的問題,但是我已經堅持了好幾天,而谷歌解決方案都沒有為我解決。
我正在按照指令驅動的方法編寫一個angular 1.4應用程序,因此對於任何實體,我都有一個或多個小部件:
問題在於“用戶擁有東西”的多樣性。
<user-widget>
<stuff-widget userid="user._id"></stuff-widget>
</user-widget>
用戶ID很好地傳遞到了小部件中,但是我想在東西小部件的鏈接函數中使用它,因為東西確實很復雜,在現實世界中,我還需要抓住其他各個部分。
我嘗試了各種方法來獲取用戶ID值(如各種其他stackoverflow討論和網絡其他地方所建議的那樣)
我對嘗試過的各種方法都一無所知: 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);
}
};
}
我是一個有經驗的初學者(第一個認真的項目),到目前為止,我的經驗是:“如果很難弄清楚,您可能做錯了方法”。
所以,
鏈接功能執行完后,您將必須等待一個摘要周期才能從使用指令的范圍中更新隔離范圍中的值。
您可以在stuffWidged中嘗試以下代碼段:
link: function(scope, element, attrs, ctrl) {
var uid, usrStuff;
scope.uid; // it is normal to be undefined here
scope.$watch('uid', function(newUid) {
uid = newUid;
scope.uid; // is ready and is same as newUid
usrStuff = ctrl.usrStuff = scope.usrStuff =
ctrl.findById(uid);
});
}
<user-widget widgetusers="model.users"></user-widget>
然后,用戶小部件模板將為:
<stuff-widget ng-repeat="stuffuser in widgetusers" userid="stuffuser._id"></stuff-widget>
<user-widget userid="user._id"> <stuff-widget userid="userid"></stuff-widget> </user-widget>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.