我将以下代码集成到我的 html 页面中:
<div ng-controller="MirrorCheckboxController">
<div ng-repeat="setting in settings">
<input type="checkbox" ng-attr-id="{{ setting.id }}">
<label ng-attr-for="{{ setting.id }}"><span class="checkbox"{{setting.name}}</span></label>
</div>
</div>
<div id="events">
<input type="checkbox" id="green">
<label for="green"><span>Sports</span></label> <br/>
<input type="checkbox" id="red">
<label for ="red"><span >University</span></label> <br/>
<input type="checkbox" id="yellow">
<label for= "yellow"><span>Friends</span></label> <br/>
<input type="checkbox" id="blue">
<label for ="blue"><span>Other</span></label> <br/>
</div>
这是我在外部 .js 文件中的 Angular 代码:
(function() {
'use strict';
var exampleApp = angular.module('exampleApp');
exampleApp.controller('MirrorCheckboxController', ['$scope', function($scope) {
$scope.settings = [{
name: 'Weather Forecast',
value: '',
id: 'mirror-1'
}, {
name: 'Time',
value: '',
id: 'mirror-2'
}, {
name: 'Traffic Situation',
value: '',
id: 'mirror-3'
}, {
name: 'Personal Schedule',
value: '',
id: 'mirror-4'
}];
}]);
})();
如果选中了 id 为“mirror-4”的 Angular 循环中的最后一个复选框,我正在寻找一种隐藏“事件”div 容器的方法。我尝试使用 JQuery 在 script-tags 的 html 文件中解决这个问题。如果代码没有引用 Angular 给出的 ID,则该代码可以正常工作。为什么下面的代码不起作用?
<script>
$('#mirror-4').change(function(){
if($(this).prop("checked")) {
$('#events').show();
} else {
$('#events').hide();
}
});
</script>
我对 Angular 非常陌生,感谢每一个帮助。
问候, 洛伦兹
最佳答案
如果你使用 Angular,你应该以 Angular 的方式来做,并尽量避免使用 jQuery。正如上面的评论中提到的,尝试使用 Angular 逻辑来处理您的请求。这是一个非常基本的 Angular example :
将ng-model
添加到您的复选框:
<input type="checkbox" ng-model="toggleEvents" ng-attr-id="{{ setting.id }}">
// If you want to display the "events container"
// per default add a `ng-init` like this:
<input type="checkbox" ng-model="toggleEvents" ng-init="toggleEvents=true" />
使用ng-if
来处理隐藏/显示:
<div ng-if="toggleEvents">
This is your Eventbox
</div>
或者为了更接近您给定的代码,您可以执行以下操作:
exampleApp.controller('MirrorCheckboxController', ['$scope', function($scope) {
// we use this to collect the checked checkboxes
$scope.checkedElements = {};
// your settings
$scope.settings = [{
name: 'Weather Forecast',
value: '',
id: 'mirror-1'
}, {
name: 'Time',
value: '',
id: 'mirror-2'
}, {
name: 'Traffic Situation',
value: '',
id: 'mirror-3'
}, {
name: 'Personal Schedule',
value: '',
id: 'mirror-4'
}];
// the method to display or hide the event container
$scope.showEvents = function(obj) {
return (!obj['mirror-4']);
}
});
在你的 html 中:
<div ng-controller="MirrorCheckboxController">
<p ng-repeat="setting in settings">
<label class="checkbox">
<input type="checkbox"
ng-id="{{setting.id}}"
ng-model="checkedElements[setting.id]" />
{{setting.name}}
</label>
</p>
<div ng-show="showEvents(checkedElements)">
<!-- your event container -->
This is shown per default, hide if checkox with id "mirror-4" is checked
</div>
</div>
还有这个 fiddle is here .
关于javascript - 在 JQuery 中从 Angular 调用 ng-attr-id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41639939/