【发布时间】:2023-03-15 03:03:01
【问题描述】:
我最近开始为一个旧的 Angular 应用程序使用(不是那么新的)组件。我正在尝试为<button/>s 等琐碎的东西制作some dumb components。
出于某种原因,我似乎无法让一种方式绑定工作!
difficultyButton 组件中的level 绑定(在difficult-button.js 中)总是返回undefined,但onLevelChosen 绑定(再次在difficulty-button.js 中)似乎具有options 的回调组件传递给它。
你们有没有看到我可能出错的地方?
这是一个演示此问题的 jsbin 链接:http://jsbin.com/rixukuh/11/edit?html,js
注意 red、green 和 blue 类是如何永远不会被应用的,因为它们永远无法抓住 vm.level 的值。
此外,控制台总是打印出LEVEL => undefined,无论单击什么按钮。
完整代码
如果需要更多上下文,这里是完整的代码。
options.tpl.html
<div class="full-page-cover">
<div class="options-grid">
<!-- some random markup -->
<div class="buttons-grid">
<difficulty-button
level="easy"
on-level-chosen="vm.chooseDifficulty(level)" >
I'm just here for having fun!
</difficulty-button>
<!-- some more `difficulty-buttons` -->
</div>
</div>
</div>
options.js
import angular from 'angular';
import DifficultyButtonModule from './difficulty-button.js';
import template from './options.tpl.html';
class OptionsController {
constructor() { /* ... */ }
chooseDifficulty(level) { /* ... */ }
}
const OptionsModule = angular.module('options', [DifficultyButtonModule.name])
OptionsModule.component('options', {
template,
controller: OptionsController,
controllerAs: 'vm'
});
export default OptionsModule;
difficulty-button.tpl.html
<button
ng-class="[
'uk-button uk-button-large',
{
easy: 'uk-button-default',
medium: 'uk-button-primary',
hard: 'uk-button-danger'
} [ vm.level ]
]"
ng-click="vm.onLevelChosen({ level: vm.level })"
ng-transclude>
</button>
difficulty-button.js
import angular from 'angular';
import template from './difficulty-button.tpl.html';
const DifficultyButtonModule = angular.module('difficultyButton', []);
DifficultyButtonModule.component('difficultyButton', {
template,
bindings: {
level: '<',
onLevelChosen: '&'
},
controllerAs: 'vm',
transclude: true
});
export default DiffButtonModule;
【问题讨论】:
-
你能提供一个小提琴吗?
-
@Gonzalo.- 当然!让我鞭打一个。
-
@Gonzalo.- 检查我的编辑!我添加了一个 jsbin 文件
-
只希望你在实际代码中使用比 document.querySelector('#difficulty-btn-tpl').innerText 更聪明的东西
-
@PetrAveryanov - 是的!
import template from './difficulty-button.tpl.html';是我在真实代码中的做法。
标签: javascript angularjs angularjs-components