有一些指令,取消先前檢查收音機組:動態添加ngModels子元素在角指令
(function (angular, $) {
'use strict';
var radioGroupDirective = function() {
return {
restrict: 'EA',
require: 'ngModel',
link: function($scope, $element, $attrs, ngModelController) {
var $radios = $element.find('input[type="radio"]');
$radios.click(function($event) {
var $radio = $($event.target);
if ($radio.data('waschecked') == true) {
$radio.prop('checked', false);
$radio.data('waschecked', false);
ngModelController.$setViewValue(null);
} else {
$radio.data('waschecked', true);
}
$radio.siblings('input[type="radio"]').data('waschecked', false);
});
},
};
};
radioGroupDirective.$inject = [];
angular.module('radio.group', []).directive('radioGroup', radioGroupDirective);
})(angular, $);
用法:
<div radio-group ng-model="fruit">
<input type="radio" ng-model="fruit" value="Apple"/>
<input type="radio" ng-model="fruit" value="Banana"/>
<input type="radio" ng-model="fruit" value="Mango"/>
</div>
它工作正常,但我想刪除重複的代碼ngModels的子輸入。就像這樣:
<div radio-group ng-model="fruit">
<input type="radio" value="Apple"/>
<input type="radio" value="Banana"/>
<input type="radio" value="Mango"/>
</div>
所以我嘗試ngModel動態編譯功能添加到所有的孩子投入
(function (angular, $) {
'use strict';
var radioGroupDirective = function ($compile) {
return {
restrict: 'EA',
require: 'ngModel',
link: function($scope, $element, $attrs, ngModelController) {
var $radios = $element.find('input[type="radio"]');
$radios.click(function($event) {
var $radio = $($event.target);
if ($radio.data('waschecked') == true) {
$radio.prop('checked', false);
$radio.data('waschecked', false);
ngModelController.$setViewValue(null);
} else {
$radio.data('waschecked', true);
}
$radio.siblings('input[type="radio"]').data('waschecked', false);
});
},
compile: function (tElement, tAttrs) {
var $radios = tElement.find('input[type="radio"]');
angular.forEach($radios, function(radio) {
$(radio).attr('ng-model', tAttrs.ngModel);
});
return {
pre: function preLink(scope, iElement, iAttrs, controller) {
},
post: function postLink(scope, iElement, iAttrs, controller) {
$compile(iElement)(scope);
},
};
},
};
};
radioGroupDirective.$inject = ['$compile'];
angular.module('radio.group', []).directive('radioGroup', radioGroupDirective);
})(angular, $);
但它會導致一個無限編譯循環和死瀏覽器
任何撥弄會更加明朗 – Shaxrillo 2015-04-02 09:45:52