Reputation: 189
I'm creating a questionnaire form using AngularJS, and I'm templatizing the different types of questions I have to keep my HTML lightweight.
HTML:
<qtnyesno qtn-variable="testVar">This is a test question. Yes or No?</qtnyesno>
testVar = {{testVar}}
JS:
var module = angular.module('app', [])
.directive('qtnyesno', function() {
return {
restrict: 'E', // must be an HTML element
transclude: true,
scope: {
valvar: '@qtnVariable',
},
template:
'<div>' +
'<label ng-transclude></label>' +
'<label class="radio inline"><input type="radio" name="rdo{{valvar}}" value="1" ng-model="{{valvar}}">Yes </label>' +
'<label class="radio inline"><input type="radio" name="rdo{{valvar}}" value="0" ng-model="{{valvar}}">No </label>' +
'<hr></div>',
replace: true,
};
});
When I use within the input tag ng-model="{{valvar}}" I get compilation errors.
When I try using instead ng-click="{{valvar}} = 0" I get no compilation errors, but my display statement to get the value of testVar never works when I click on the radio buttons.
How would I fix this such that the last line of my HTML gets properly updated with the value of testVar when I click on the buttons?
I'm using AngularJS along with Bootstrap. I'm fairly new to both frameworks, so I'm not sure if this is even the best way to go about doing this.
Upvotes: 1
Views: 2501
Reputation: 12477
Brandon's right, use =
in your isolate scope to get the two-way binding, but there's one more thing you have to do: remove the curly braces from around your ng-model
declarations.
ng-model
declarations take an angular expression and evaluate them in the scope, so there's no need for the braces to force evaluation. In fact, the braces will mess things up.
// so just
ng-model="valvar"
Here's a fiddle with your code with these changes.
Upvotes: 1
Reputation: 159115
To get bi-directional binding in your isolate scope, use =
:
scope: {
valvar: '=qtnVariable',
},
@
makes the resulting scope variable a string with interpolation.
Upvotes: 1