Input text box, generate li element, and li element can bind events
In fact, this is a problem that may become very complicated. In reality, there are many solutions. I will write you the simplest reference:
javascript
// 在某一個 controller 里: function DemoController() { var vm = this // 用了 "controller as" 語法的時候會這樣寫,vm 代表 viewModel vm.listItems = [] // 初始化一個數(shù)組用于保存將要生成的 li vm.listItem = '' // 用于綁定 input;不聲明其實也可以,這里是為了讓你看清楚 // 綁定在 input 上的方法,把新的 listItem 加入數(shù)組,然后重置它 vm.addItem = function() { vm.listItems.push(vm.listItem) vm.listItem = '' } // 綁定在 li 上的方法,接受 $event 參數(shù),你可以利用它獲取當(dāng)前被點(diǎn)擊的 li vm.itemClickHandler = function(event) { var currentElement = event.target // ... } }
Then in the corresponding template:
html
<input ng-model="vm.listItem"> <button ng-click="vm.addItem()">添加</button> <ul> <li ng-repeat="item in vm.listItem" ng-click="vm.itemClickHandler($event)">{{item}}</li> </ul>
This is an idea. There are too many variable factors in reality, so it’s hard to go into details one by one. The key points to consider when dealing with similar problems are pretty much the following:
input
when added, but this is not the way of writing in angular, this is the way of writing in jQuery$event
的對象,因為它使得我必須在 controller
to mix in code related to DOM or Event instead of business logic. Of course there are many solutions, such as: listItem.text
保存文字內(nèi)容,然后在添加的時候給它生成一個遞增的 listItem.id
。這樣做有很多好處,比如說 ng-repeat
的時候可以 track by
,控制模版輸出也會更靈活,綁定的事件處理方法可以不傳 $event
而是傳 item
或 item.id
you can waitFor dynamically inserted HTML, which contains ng parameters, angularjs generally does not parse it twice.
You can use dependency injection to call $compile to rewrite and compile local code.