0

I'm new to AngularJS and have recently begun experimenting with creating tables and the ng-repeat functionality. I had an idea to write a JS object where every object has a respective name and a HTML button element associated with it. I'm able to create the list of objects without a problem, but the issue I'm running into is how to display the information; specifically, how to display each object's button element.

Below is the code I have for displaying each object in a list:

<!DOCTYPE html>
<html>
<script 
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">
<ul>
    <li ng-repeat="x in names">
        {{x.name + ', ' + x.button}}
    </li>
</ul>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $interval) {
    $scope.names = [{name:'Mike',button:document.createElement('button')}]
});
</script>

</body> 
</html>

Currently my results look like:

enter image description here

And what I would like to see is:

enter image description here

2 Answers 2

2

You should create the button with the html tag. Like this:

<div ng-app="myApp" ng-controller="myCtrl">
<ul>
    <li ng-repeat="x in names">
        {{x.name}}
        <button ng-click="...">{{x.button}}</button>
    </li>
</ul>
</div>

Its the standard way to do it with AngularJS and will give you more freedom to use ng directives and all.

Sign up to request clarification or add additional context in comments.

Comments

1

No idea what you want to create an element. Just use text for the property value and add appropriate markup in the template.

Use components or directives for any dom methods. They don't belong in controllers

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $interval) {
    $scope.names = [{name:'Mike',button:'Button name'}]
});
<!DOCTYPE html>
<html>
<script 
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">
<ul>
    <li ng-repeat="x in names">
        {{x.name}}<button>{{x.button}}</button>
    </li>
</ul>
</div>

<script>

</script>

</body> 
</html>

2 Comments

You say that DOM methods don't belong in controllers. Why is that?
Because controllers shouldn't know anything about the view structure. They are for managing the model for the view.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.