我创建了Angular指令,但不会与一起运行ng-repeat
。我不知道为什么 第二个指令成功运行。
JavaScript:
angular.module('myApp',[])
.controller('Ctrl',['$scope', function ($scope) {
$scope.vvv = [];
$scope.bbb = [];
$scope.testdatas = [{text : 0},{text : 1},{text : 2},{text : 3}]
}])
.directive('wstCheckbox', function () {
return {
restrict:'EA',
replace:true,
template:'<div ng-transclude></div>',
scope:{
modelname : '=' //ths is the model
},
transclude:true,
link : function (scope,element,attrs) {
console.log(element)
$(element).find('input[type=checkbox]').on('change', function () {
scope.modelname = [];
scope.$apply(function () {
$(element).find('input[type=checkbox]:checked').each(function () {
scope.modelname.push($(this).val());
})
})
})
}
}
})
HTML:
<div>
<wst-checkbox modelname="vvv">
<div>{{vvv}}</div>
<input type="checkbox" name="test" value="data.text" ng-repeat="data in testdatas"/>
</wst-checkbox>
<wst-checkbox modelname="bbb">
<div>{{bbb}}</div>
<input type="checkbox" name="test" value="0" id="4"/><label for="4">index 0</label>
<input type="checkbox" name="test" value="1" id="5"/><label for="5">index 1</label>
<input type="checkbox" name="test" value="2" id="6"/><label for="6">index 2</label>
<input type="checkbox" name="test" value="3" id="7"/><label for="7">index 3</label>
</wst-checkbox>
</div>
问题在于,在您绑定到更改事件的那一点上,angular尚未呈现ng-repeat。如果您设置了超时时间以渲染所有内容,那么它应该可以正常工作。
这是一个正在工作的柱塞
link : function (scope,element,attrs) {
console.log(element)
$timeout(function(){
$(element).find('input[type=checkbox]').on('change', function () {
scope.modelname = [];
scope.$apply(function () {
$(element).find('input[type=checkbox]:checked').each(function () {
scope.modelname.push($(this).val());
})
})
})
},0);
}
我建议您在输入中使用ng-change和ng-model,并以更角度的方式进行所有操作。您应该意识到使用transclude的指令中的作用域可能会按您期望的方式工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句