How do I properly build an AngularJS labeled radio input directive? -
i realize angularjs has input[radio] directive , want leverage as possible.
i created jsfiddle here, can't figure out how ng-model property work properly. i'm selecting each radio, selectedvalue doesn't change.
also, please tell me i'm doing wrong here. i'm sure make other improvements.
the html:
<div data-ng-controller="controller"> <div data-ng-repeat="radio in radios" data-ng-model="selectedvalue" data-name="radio1" data-label="{{radio.label}}" data-value="{{radio.value}}" data-labeled-radio></div> <br> selected value: {{selectedvalue}} </div> the javascript:
angular.module('app', []) .controller('controller', function($scope) { $scope.selectedvalue = 'foo'; $scope.radios = [ { label: 'foo', value: 'foo' }, { label: 'bar', value: 'bar' } ]; }) .directive('labeledradio', function(){ return { require: ['ngmodel', 'value'], restrict: 'a', replace: true, template: [ '<label class="radio">', ' <input class="radio__input" type="radio" data-ng-model="ngmodel" name="{{name}}" value="{{value}}">', ' <span class="radio__label">{{label}}</span>', '</label>' ].join(''), scope: { ngmodel: '=', label: '@', name: '@', value: '@' } } });
because of way prototypal inheritance works in javascript, can't use primatives on scope 2-way databinding. therefore way fix change selectedvalue object...
angular.module('app', []) .controller('controller', function($scope) { $scope.selectedvalue = { value: 'foo' }; $scope.radios = [ { label: 'foo', value: 'foo' }, { label: 'bar', value: 'bar' } ]; }) <div data-ng-controller="controller"> <div data-ng-repeat="radio in radios" data-ng-model="selectedvalue.value" data-name="radio1" data-label="{{radio.label}}" data-value="{{radio.value}}" data-labeled-radio></div> <br> selected value: {{selectedvalue.value}} </div> fiddle: http://jsfiddle.net/gdnkw/
for full explanation, see here: https://github.com/angular/angular.js/wiki/understanding-scopes
Comments
Post a Comment