我正在尝试使用 angular 中的 css 创建 iphone 样式的 Toggle Button
但问题是动态按钮文本变量第一次未评估 "{{v1['btn2']}}" ,但与静态文本一起工作正常
jsFiddle 的网址:
http://jsfiddle.net/vishalvasani/z5SNc/3/
下面是我的代码:
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>