基本设置:
我有一个模态表单,里面有一个自定义指令(子元素)。自定义指令是一个按钮。该模式还包含一个输入复选框。
最终目标:
只要“选中”复选框,就应启用自定义指令/按钮元素。如果该复选框为“未选中”,则应禁用自定义指令/按钮。
到目前为止我所拥有的又名我的思考过程:
在“modalController”中,我在复选框输入上放置了一个 ng-model 以动态更改变量的值(isChecked)。当检查输入时,它将 $scope.isChecked 值设置为 true,当未检查时,$scope.isChecked 为 false。
为了禁用该按钮,我会将“isChecked”的值从 modalController 传递到自定义指令,其中它的值可以放入指令模板内按钮上的 ng-checked 表达式中(见下文)。
问题
当我尝试此解决方案时,控制台日志显示错误“inputCheck 未定义”。页面加载后就会发生这种情况,因此在用户单击复选框之前就会打印控制台日志。关于如何实现这项工作有什么想法吗?
模态 html:
<div ng-controller= "modalController">
<input type="checkbox" ng-model="isChecked">
<button-directive inputCheck="isChecked"></button-directive>
</div>
ButtonDirective.js:
angular.module('starter').directive('buttonDirective', function ($uibModal) {
return {
restrict: "EA",
templateUrl: "app/directives/button-directive.html",
scope: {
inputCheck: "@"
},
controller: ['$scope', function ($scope) {
console.log(inputCheck);
}]
};
});
button-directive.html:
<button ng-checked="inputCheck">
你做错了。 $scope 变量与指令范围声明不同。
每个子项,包括指令,都在 $scope 范围内,明白吗?
因此您的指令声明不需要该范围,请将其删除。
angular.module('starter').directive('buttonDirective', function ($uibModal) {
return {
restrict: "EA",
templateUrl: "app/directives/button-directive.html"
};
});
而你的模态,不需要传递你的 inputCheck 属性。
<div ng-controller= "modalController">
<input type="checkbox" ng-model="isChecked">
<button-directive></button-directive>
</div>
然后你的指令 html 就变成了
<button ng-checked="isChecked">
看这个
按照您的方式工作。
你传递的属性是错误的,在我看来,AngularJS 有一件坏事,那就是当你将值传递给像 inputCheck 这样的指令时,你必须用 hiphen 来写它,所以它需要是
input-check
<button-directive input-check="isChecked"></button-directive>
并且你的范围声明必须使用等号
scope: {
inputCheck: "="
},
您应该进行以下更改:
<button-directive input-check="isChecked"></button-directive>
scope: {
inputCheck: "="
}
<button ng-disabled="inputCheck">
当您使用时:
return {
scope: { varName: '='
},
controller: function($scope){
console.log($scope.varName); // anything from RETURN -> SCOPE gets automatically inserted into $scope
}