导航栏组件数据绑定无法使用驼峰命名?求资料及解决方案
Hey there! Let's tackle your navbar component binding issue head-on. First off: yes, you absolutely can use camelCase variable names for component data binding—it's not only allowed, but it's actually a recommended practice for improving code readability, just like you want for your team.
The Root of Your Problem
The issue you're hitting comes down to how HTML handles attribute names: HTML is case-insensitive, so when you write titleId='vm.titleData' in your template, browsers automatically convert that attribute to all lowercase (titleid). But your component's binding uses titleId (camelCase), so AngularJS can't match the two up, leaving you with broken data flow.
Let's Fix Your Code
Here's how to adjust your template and keep using camelCase in your component:
Step 1: Use Kebab-Case in the HTML Template
Replace the camelCase attribute titleId with kebab-case (title-id) in your navbar component usage. AngularJS automatically maps kebab-case HTML attributes to camelCase component bindings:
<navbar-component theme="newux" class="screenOnly" title='projData' title-id="vm.titleData" data='{{vm.project.id}}'> </navbar-component>
Step 2: Keep Your Component Bindings As-Is
You don't need to change anything in your component's bindings—camelCase works perfectly here:
bindings: { theme: "@", title:"@", titleId:"<", data:"@" }
Bonus: Understand Your Binding Symbols
A quick note on the binding syntax you're using, to make sure you're getting the most out of them:
@: For passing string values (including interpolated strings like{{vm.project.id}}).<: For one-way data binding (ideal for passing objects or reference types from the parent scope to the component). SincetitleIduses<, you don't need{{}}aroundvm.titleDatain the template—AngularJS handles the binding directly.
Additional Checks
To make sure everything works smoothly:
- Verify that
vm.titleDataexists and has a value in your parent controller (try logging it withconsole.log(vm.titleData)to confirm). - Ensure you're registering your component with AngularJS's
.component()method (not.directive()), as component bindings are designed to work with this syntax.
Wrap-Up
CamelCase bindings are fully supported—you just need to pair them with kebab-case in your HTML template to account for HTML's case insensitivity. This setup will keep your team's code clean, readable, and flexible with naming conventions.
内容的提问来源于stack exchange,提问作者Tom Edwards

