AngularJS中如何在ng-bind-html中监听ng-model值
Alright, let's get your name display synced up with the text input properly! Here's how to replace that {{}} placeholder with your desired initial value ("Habib") and make the content update in real-time as you type in the text box.
Option 1: Vue.js (Most Common for {{}} Syntax)
Since you're using {{}} interpolation, Vue.js is likely your framework of choice. Here's how to set up two-way data binding:
- Define a reactive data property (e.g.,
name) with your initial value "Habib" - Use
v-modelto bind the text input to this property - Replace
{{}}with{{ name }}to render the reactive value
<div id="app"> <input type="text" v-model="name" placeholder="Update your name here"> <p>My name is: {{ name }}</p> </div> <script> new Vue({ el: '#app', data() { return { name: 'Habib' // Initial value matches your desired output } } }) </script>
How it works: v-model automatically syncs the input's value with the name data property. Every time you type in the text box, name updates, and the {{ name }} interpolation re-renders the latest value instantly.
Option 2: React.js
If you're using React instead, you'll use state to track the input value and update the display:
import { useState } from 'react'; function NameDisplay() { // Initialize state with "Habib" const [name, setName] = useState('Habib'); // Update state when input changes const handleInputChange = (e) => { setName(e.target.value); }; return ( <div> <input type="text" value={name} onChange={handleInputChange} placeholder="Update your name here" /> <p>My name is: {name}</p> </div> ); } export default NameDisplay;
How it works: The useState hook creates a reactive name state. The input's value is tied to this state, and the onChange handler updates the state whenever you type. React re-renders the component with the new state value, keeping the display in sync.
Option 3: Vanilla JavaScript (No Framework)
If you're working with plain HTML/JS, you can manually wire up the input and display:
<input type="text" id="nameInput" value="Habib"> <p id="nameDisplay">My name is: Habib</p> <script> const input = document.getElementById('nameInput'); const displayElement = document.getElementById('nameDisplay'); // Update display when input changes input.addEventListener('input', () => { displayElement.textContent = `My name is: ${input.value}`; }); </script>
How it works: We listen for the input event on the text box, then update the paragraph's text content to match the input's current value. The initial value is set directly in the HTML to match your desired starting output.
内容的提问来源于stack exchange,提问作者habib

