【发布时间】:2015-07-16 19:19:16
【问题描述】:
我有一个为“开关”创建的指令(元素),它使用 input[checkbox]。
只要不选中复选框的初始状态,一切正常。但是如果我想将初始状态设置为选中(基于我的控制器值),那么它总是相反。为什么当控制器变量说应该检查时没有检查该值?
HTML
<a-switch toggle-state="vm.doSomething"></a-switch>
指令 Html
<div class="switch-container">
<input type="checkbox" id="switch" />
<label for="switch" class="pm-switch"></label>
</div>
Javascript 控制器
vm.doSomething = {
state: true
};
指令
angular.module('material')
.directive('aSwitch', [
'$timeout', function($timeout) {
return {
templateUrl: 'elements/material/switch/switch.html',
transclude: false,
restrict: 'E',
scope: {
toggleState: '=',
},
link: function (scope, element) {
element.on('click touchstart', function (event) {
if (event.srcElement && event.srcElement.id && event.srcElement.id === "switch") {
event.stopPropagation();
$timeout(function() {
scope.toggleState.state = !scope.toggleState.state;
});
}
});
}
};
}
]);
我意识到为了设置泛型的选中状态
<input type="checkbox" />
我只需要添加属性“checked”,比如
<input type="checkbox" checked />
但是如果它在我的指令的 html 中,我该怎么做呢?
【问题讨论】:
-
你可以通过
<input type="checkbox" id="switch" ng-model="toggleState.state"/>来解决这个问题,然后超时函数将是`$timeout(function() { scope.toggleState.state = scope.toggleState.state? scope.toggleState.state: false; }); -
哇,使用这种方法否定了我的指令中对“链接”部分的需求,请将其添加为答案,以便我给你积分
-
酷,我会在一个小时内完成..
标签: javascript html angularjs checkbox angularjs-directive