Trying to implement an iPhone-style Toggle Button using CSS in Angular.
The issue I am facing is that the dynamic button text variable "{{v1['btn2']}}" is not being evaluated properly the first time, although it works fine with static text.
URL for the jsFiddle example:
http://jsfiddle.net/vishalvasani/z5SNc/3/
Here is the provided code:
angular.module('test').controller('myctrl', function($scope){
$scope.v1={
"status":"1",
"btn1":"On",
"btn2":"Off"
}
$scope.v2={
"status":"1"
}
});
angular.module('test').directive('btnSwitch', function(){
return {
restrict : 'AE',
require : 'ngModel',
link : function(scope, element, attrs, ngModel){
ngModel.$render = function() {
render();
};
var render=function(){
var val = ngModel.$viewValue;
var open=angular.element(element.children()[0]);
var closed=angular.element(element.children()[1]);
if(val)
{
closed.html(closed.attr("text"));
closed.addClass('btnOnSelected');
open.html(" ");
open.removeClass('btnOffSelected');
}
else{
open.html(open.attr("text"));
open.addClass('btnOffSelected');
closed.removeClass('btnOnSelected');
closed.html(" ");
}
};
element.bind('click', function() {
scope.$apply(toggle);
});
function toggle() {
var val = ngModel.$viewValue;
ngModel.$setViewValue(!val);
render();
}
if(!ngModel){
return;
}
render();
}
};
});
HTML:
<div ng-app="test">
<div ng-controller="myctrl">
<div class="pull-left" btn-switch ng-model="v1['status']">
<div class="pull-left btnCS btnOff" text="{{v1['btn1']}}"> </div>
<div class="pull-left btnCS btnOn btnOnSelected" text="{{v1['btn2']}}"></div>
</div>
<div class="clearFix" style="height:20px"></div>
<hr />
<div class="pull-left" btn-switch ng-model="v2['status']">
<div class="pull-left btnCS btnOff" text="On"> </div>
<div class="pull-left btnCS btnOn btnOnSelected" text="Off"></div>
</div>
</div>
</div>