I want to get the values of li elements from a ul element, in AangularJS controller and want to store them in an array.
Html Code
<ul id="list" my-directive>
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
<li>E</li>
</ul>
Controller
app.controller('myCtrl', function($scope) {
$scope.newList = [];
$scope.newList = $('#list li').html();
})
What i'm doing wrong?
Why don't you rather render all li
element using ng-repeat
only?
<ul id="list">
<li ng-repeat="alphabet in alphabets">A</li>
</ul>
Code
$scope.alphabets = ["A", "B", "C", "D", "E"]
May be you have some special case where you have rendering data from server side using view engine. Though below is the way to accomplish using directive(still I'd recommend you to use 1st suggested way only)
Markup
{{myList}}
<ul my-directive="myList">
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
<li>E</li>
</ul>
Directive
.directive('myDirective', function() {
return {
link: function(scope, element, attrs) {
var list = scope[attrs.myDirective] = []
Array.from(element.find('li')).forEach(function(li) {
list.push(li.innerText)
});
}
}
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.