【发布时间】:2015-07-13 20:39:18
【问题描述】:
由于某种原因,我无法根据我在 SO 上看到的其他示例来完成这项工作。
这是我的指令:
(function () {
angular.module('materialDesign')
.directive('aSwitch', directive);
function directive() {
return {
templateUrl: 'elements/material/switch/switch.html',
transclude: false, // I've tried true here
restrict: 'E',
scope: {
enabled: '=',
toggleState: '=',
},
link: function(scope, element) {
element.on('click touchstart', function() {
scope.toggleState = !scope.toggleState;
});
}
};
}
})();
以及在切换开关/复选框时我想要更改的控制器范围值:
$scope.hideInactive = true;
html:
<a-switch toggle-state="hideInactive"></a-switch>
在我的 html 页面的更下方,我有这个:
<div ng-show="!hideInactive">
<!-- stuff -->
</div>
编辑:
这个版本“现在可以工作”,但是当我第二次点击我的开关/复选框时,element.on 会触发两次,这会将我的范围值翻转回原来的值.....基本上,它是不要让我“取消选中”我的切换。
angular.module('material')
.directive('aSwitch', [
'$timeout', function($timeout) {
return {
templateUrl: 'elements/material/switch/switch.html',
transclude: false,
restrict: 'E',
scope: {
enabled: '=',
toggleState: '=',
},
link: function (scope, element) {
element.on('click touchstart', function () {
$timeout(function () {
scope.toggleState.state = !scope.toggleState.state;
scope.$apply();
});
});
}
};
}
]);
编辑和最终解决方案:
这是修复了所有问题的更新后的指令链接属性。我想补充一点,还使用了 Oleg Yudovich 的答案(将对象作为属性而不是 true/false 本身传递)
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;
});
}
});
}
【问题讨论】:
标签: angularjs angularjs-directive angularjs-scope