Recently, I've been experimenting with Angular directives and encountered a peculiar issue... Check out the code snippet below:
<!DOCTYPE html>
<html>
<head>
<title>Directive test</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.js"></script>
<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller('mainCTRL', function($scope) {});
app.directive('listItems', function() {
return {
restrict : 'E',
transclude : true,
scope : {
items : '='
},
controller : function($scope) {
/**
* @param item item being inserted
*/
$scope.addQuestion = function() {
//Define the item list (if undefined)
if(!$scope.listOfItems) $scope.listOfItems = [];
//add the item
$scope.listOfItems.push({
question : $scope.question
});
console.log($scope.listOfItems);
};
},
template : '<div>Question: <input type="text" ng-model="question" />' +
'<button ng-click="addQuestion()">Add question</button>' +
'<div><ng-transclude></ng-transclude></div>' +
'</div>'
};
});
</script>
</head>
<body ng-app="myApp" ng-controller="mainCTRL">
<list-items items="listOfItems">
<div ng-repeat="item in listOfItems track by $index">
{{item.question}}
</div>
</list-items>
</body>
</html>
I have managed to push objects into the array successfully, but for some reason, they do not repeat as expected. Any ideas why this might be happening?
<list-items items="listOfItems">
<div ng-repeat="item in listOfItems track by $index">
{{item.question}}
</div>
</list-items>
Your help is greatly appreciated.