最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Reverse checkbox value in angular2 - Stack Overflow

programmeradmin0浏览0评论

Having some troubles reversing the checkbox value in Angular 2.

In Angular 1.x we could make a directive like below.

.directive('invertValue', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, ngModel) {
      ngModel.$parsers.unshift(function(val) { return !val; });
      ngModel.$formatters.unshift(function(val) { return !val; });
    }
  };
})

Having some troubles reversing the checkbox value in Angular 2.

In Angular 1.x we could make a directive like below.

.directive('invertValue', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, ngModel) {
      ngModel.$parsers.unshift(function(val) { return !val; });
      ngModel.$formatters.unshift(function(val) { return !val; });
    }
  };
})
Share Improve this question edited Jun 15, 2017 at 3:41 Vamshi 9,3614 gold badges40 silver badges55 bronze badges asked Jun 15, 2017 at 2:02 kplateskplates 7301 gold badge7 silver badges17 bronze badges 2
  • you mean making it false if its true? – Sajeetharan Commented Jun 15, 2017 at 2:03
  • Yeah the value is in my object is true however the checkbox should display as false. Without changing ngModel to false. i was hoping to create this as a directive so its reusable like the above code – kplates Commented Jun 15, 2017 at 2:05
Add a ment  | 

1 Answer 1

Reset to default 7

why you need directive for this simple thing

you can achieve like this

<input type="checkbox" [checked]="!value" (change)="value= !value" />
发布评论

评论列表(0)

  1. 暂无评论