漂亮男人2017-05-15 16:55:10
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 = [] // 初始化一个数组用于保存将要生成的 li vm.listItem = '' // 用于绑定 input;不声明其实也可以,这里是为了让你看清楚 // 绑定在 input 上的方法,把新的 listItem 加入数组,然后重置它 vm.addItem = function() { vm.listItems.push(vm.listItem) vm.listItem = '' } // 绑定在 li 上的方法,接受 $event 参数,你可以利用它获取当前被点击的 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
保存文字内容,然后在添加的时候给它生成一个递增的 listItem.id
。这样做有很多好处,比如说 ng-repeat
的时候可以 track by
,控制模版输出也会更灵活,绑定的事件处理方法可以不传 $event
而是传 item
或 item.id
you can waitphpcn_u15822017-05-15 16:55:10
For 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.