javascript - AngularJS custom directive breaks data binding on radio element -
i have set basic boolean binding on radio element. when user selects "true" radio element, should display div beneath further options. when view loads, i'd ensure elements "true" have div's beneath displayed.
prior angular, 2 two things jquery:
// pseudo-ish code $(element).on("click", function() { /* show/hide div */ }); $(element:checked).each(function() { /* show child div if val() == 'true' */}
with angular, needed directive that. directive want do, broke data binding element, element no longer checked if model set true/false.
- how data binding work again "true" radio checked, , div shows?
- any suggestions on improving directive/code? angular newbie here, loving framework far!
here's fiddle shows it:
http://jsfiddle.net/nloding/slpbg/
here's code:
html:
<div ng-app="myapp" ng-controller="testcontroller"> <input type="radio" name="transfercontrol" data-test-control required data-ng-value="true" data-ng-model="transfer" /> true<br/> <input type="radio" name="transfercontrol" data-test-control data-ng-value="false" data-ng-model="transfer" /> false <div class="testcontrols">show stuff here if true</div> </div>
js:
var myapp = angular.module('myapp', []) .directive('testcontrol', function() { return { require: 'ngmodel', restrict: 'a', replace: false, transclude: true, scope: { enabled: "=ngmodel" }, link: function (scope, element) { if (scope.enabled && element.val().tolowercase() === 'true') { element.nextall('div.testcontrols').first().show(); } element.bind('click', function() { if ( element.val().tolowercase() === 'true') { element.nextall('div.testcontrols').first().show(); } else { element.nextall('div.testcontrols').first().hide(); } }); return; } }; }); function testcontroller($scope) { $scope.transfer = true; }
what trying pretty simple , can without needing write directive.
replace data-ng-value
s value
s.
use ng-show
hide/show contents based on value of transfer
.
<div ng-app="myapp" ng-controller="testcontroller"> <input type="radio" name="transfercontrol" ng-model="transfer" value="true"/> true<br/> <input type="radio" name="transfercontrol" ng-model="transfer" value="false"/> false <!-- compare against 'true' instead of true --> <div ng-show="transfer=='true'">show stuff here if true</div> </div>
controller:
function testcontroller($scope) { /* since attribute values in html strings */ /* $scope.transfer = true; wont work */ /* use string instead */ $scope.transfer = "true"; }
Comments
Post a Comment