呼叫连接功能
问题描述:
我创造了一个AngularJS指令,使用引导插件“复选框切换”呼叫连接功能
我发起指令的link
函数内的插件,但它似乎在ng-checked
指令被解析之前调用的函数,所以我总是得到未检查的开关
我试图在插件初始化之前添加一个超时 - 它在延迟之后按预期工作,这支持我假设问题是执行顺序)
这是我的Javascript和HTML:
var app = angular.module('MyApp',[])
.controller('MyCtrl', function($scope){
$scope.files = [
{name: 'a.txt', valid: true},
{name: 'b.txt', valid: false},
{name: 'c.txt', valid: true}
];
}).directive('switch', function(){
function link(scope, element, attrs) {
var cb = $(element).find('input');
cb.bootstrapSwitch({
onText: 'Valid',
offText: 'Error',
offColor: 'danger',
onSwitchChange: function(e, val){
scope.file.valid = val;
scope.$digest();
}
});
};
return {
link: link,
restrict: 'E',
template: '<input type="checkbox" ng-checked="file.valid" />'
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.1/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="//cdn.rawgit.com/nostalgiaz/bootstrap-switch/master/dist/css/bootstrap3/bootstrap-switch.min.css" rel="stylesheet"/>
<script src="//cdn.rawgit.com/nostalgiaz/bootstrap-switch/master/dist/js/bootstrap-switch.min.js"></script>
<div ng-app="MyApp">
<div ng-controller="MyCtrl">
<div ng-repeat="file in files">
<span>{{file.name}}</span> The Switch: <switch file="file" />
</div>
</div>
</div>
答
您可以直接设置在使用state: scope.file.valid
您的链接功能的状态。否则,你必须使用timeout
。
var app = angular.module('MyApp',[])
.controller('MyCtrl', function($scope){
$scope.files = [
{name: 'a.txt', valid: true},
{name: 'b.txt', valid: false},
{name: 'c.txt', valid: true}
];
}).directive('switch', function(){
function link(scope, element, attrs) {
var cb = $(element).find('input');
cb.bootstrapSwitch({
onText: 'Valid',
offText: 'Error',
offColor: 'danger',
state: scope.file.valid,
onSwitchChange: function(e, val){
scope.file.valid = val;
scope.$digest();
}
});
};
return {
link: link,
restrict: 'E',
template: '<input type="checkbox" ng-checked="file.valid" />'
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.1/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="//cdn.rawgit.com/nostalgiaz/bootstrap-switch/master/dist/css/bootstrap3/bootstrap-switch.min.css" rel="stylesheet"/>
<script src="//cdn.rawgit.com/nostalgiaz/bootstrap-switch/master/dist/js/bootstrap-switch.min.js"></script>
<div ng-app="MyApp">
<div ng-controller="MyCtrl">
<div ng-repeat="file in files">
<span>{{file.name}}</span> The Switch: <switch file="file" />
</div>
</div>
</div>
嘿,10X - 它的工作在我的情况。但它仍然听起来很奇怪,在Angular中没有解决方案。 这里的解决方案适合我的情况,但可能不适合其他人 – 2014-11-02 21:32:25