Reputation: 415
Pretty new to Angular, I have an ng-repeat, that shows severl input boxes, each should have their own ng-model name, but the ng-repeat does not populate the ng-model with the name, and crashes if I try to build the watcher {{ }} around it (i.e. ng-model="{{data.id}}
My app.js:
angular.module('app', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.data = {
dataSet: null,
inputs: [
{id: 'data1', name: 'Option A', type:'input', preFill:"no.A"},
{id: 'data2', name: 'Option B', type:'input', preFill:"no.B"},
{id: 'data3', name: 'Option C', type:'input', preFill:"no.C"}
],
};
}]).directive('formPanel', function() {
return {
restrict: 'E',
scope: {
info: '='
},
template: '<div ng-controller="ExampleController"><form name="myForm">'+
'<label for="{{option.name}}" ng-repeat="option in data.inputs"><br />'+
'Input {{option.name}}:'+
'<input ng-model="option.id" id="{{option.id}}" name="{{option.name}}" '+
'type="{{option.type}}" class="form-control">'+
' </label></form><hr>'+
'<span>data: = {{ data1}} , {{data2}}, {{data3}}.</span><br/>'+
'</div>' };
});
})
and the html:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="app" >
<form-panel info="data"></form-panel>
</body>
</html>
I Tried in this Plunker: Plunker Link
So as you can see, the ng-model is not bound(?) and probably for the same reason, the $scope name is appearing instead inside the input as data, instead of as the name of the data to be bound to.
i.e. should read ng-model="data1", but instead reads as ng-model="option.id"
Upvotes: 0
Views: 345
Reputation: 196
Please check the HTML code below:
<div>
<form name="myForm">
<label for="{{option.name}}" ng-repeat="option in data.inputs"><br />
Input {{option.name}}:
<input ng-model="option.id" id="{{option.id}}" name="{{option.name}}"
type="{{option.type}}" class="form-control"
placeholder="{{ option.preFill }}">
</label>
</form>
<hr>
<tt>data: = {{ data.inputs[0].id }} , {{data.inputs[1].id}}, {{data.inputs[2].id}}.</tt><br/>
</div>
Have modified the code and you can find it in Plunker link
Upvotes: 1
Reputation: 678
First, you should attach the controller to the app, just declaring it won't do.
You can do this by adding the attribute ng-controller="ExpampleController", or adding the controller to the directive:
restrict: 'E',
controller: 'ExampleController'
template:...
But if you add it to the directive, you just need to place the element <form-panel>
and you don't have to pass it any info.
In addition, you can't interpolate ng-model="{{someData}}" as the expression is already evaluated without the curly braces
Upvotes: 1