我正在尝试使用AngularJS创建一个checkBox,我找到了这个代码: http://jsfiddle.net/t7kr8/211/
并按照其步骤执行我的代码:
JS文件:
'use strict';
var app = angular.module('myApp.Carto', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/Carto', {
templateUrl: 'Carto/carto.html',
controller: 'CartoCtrl'
});
}])
app.controller('CartoCtrl', function($scope) {
$scope.array = [];
$scope.array_ = angular.copy($scope.array);
$scope.list = [{
"id": 1,
"value": "apple",
}, {
"id": 3,
"value": "orange",
}, {
"id": 5,
"value": "pear"
}];
});
app.directive("checkboxGroup", function() {
return {
restrict: "A",
link: function(scope, elem) {
// Determine initial checked boxes
if (scope.array.indexOf(scope.item.id) !== -1) {
elem[0].checked = true;
}
// Update array on click
elem.bind('click', function() {
var index = scope.array.indexOf(scope.item.id);
// Add if checked
if (elem[0].checked) {
if (index === -1) scope.array.push(scope.item.id);
}
// Remove if unchecked
else {
if (index !== -1) scope.array.splice(index, 1);
}
// Sort and update DOM display
scope.$apply(scope.array.sort(function(a, b) {
return a - b;
}));
});
}
};
});
但是,当我在浏览器中运行代码时,会出现复选框,但我无法查看这些框,这是否意味着该指令不起作用? 我无法弄清楚出了什么问题,因为我几乎只是复制了上面提供的链接中的代码,你能帮我解决一下吗?
提前谢谢
PS:我认为这是由于实现,但我仍然不知道如何或如何解决它答案 0 :(得分:1)
我认为你在模块名称上犯了一个错误。 我重新创建了示例代码,它完全正常:JSFiddle
代码:
var myApp = angular.module('myApp', []);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
$scope.array = [];
$scope.array_ = angular.copy($scope.array);
$scope.list = [{
"id": 1,
"value": "apple",
}, {
"id": 3,
"value": "orange",
}, {
"id": 5,
"value": "pear"
}];
}
myApp.directive("checkboxGroup", function() {
return {
restrict: "A",
link: function(scope, elem) {
// Determine initial checked boxes
if (scope.array.indexOf(scope.item.id) !== -1) {
elem[0].checked = true;
}
// Update array on click
elem.bind('click', function() {
var index = scope.array.indexOf(scope.item.id);
// Add if checked
if (elem[0].checked) {
if (index === -1) scope.array.push(scope.item.id);
}
// Remove if unchecked
else {
if (index !== -1) scope.array.splice(index, 1);
}
// Sort and update DOM display
scope.$apply(scope.array.sort(function(a, b) {
return a - b
}));
});
}
}
});
HTML:
<div ng-controller="MyCtrl">
<div ng-repeat="item in list">
<input type="checkbox" checkbox-group />
<label>{{item.value}}</label>
</div>
</div>
答案 1 :(得分:0)
错误是由于bootstrap和Materialize的存在,显然两者之间存在冲突,当我删除bootstrap时,一切运行良好