I'm trying to put together an Angular directive that will be a replacement for adding
我正在尝试组合一个Angular指令,它将替代添加
ng-disabled="!canSave(schoolSetup)"
On a form button element where canSave
is a function being defined in a controller something like the following where the parameter is the name of the form.
在表单按钮元素上,其中canSave是在控制器中定义的函数,类似于以下内容,其中参数是表单的名称。
$scope.canSave = function(form) {
return form.$dirty && form.$valid;
};
Ideally I'd love the directive on the submit button to look like this.
理想情况下,我喜欢提交按钮上的指令看起来像这样。
can-save="schoolSetup"
Where the string is the name of the form.
字符串是表单的名称。
So... how would you do this? This is as far as I could get...
那么......你会怎么做?这是我能得到的......
angular.module('MyApp')
.directive('canSave', function () {
return function (scope, element, attrs) {
var form = scope.$eval(attrs.canSave);
function canSave()
{
return form.$dirty && form.$valid;;
}
attrs.$set('disabled', !canSave());
}
});
But this obviously doesn't bind properly to the form model and only works on initialisation. Is there anyway to bind the ng-disabled directive from within this directive or is that the wrong approach too?
但这显然不能正确绑定到表单模型,只能用于初始化。无论如何都要从这个指令中绑定ng-disabled指令,或者这也是错误的方法?
2 个解决方案
#1
3
angular.module('MyApp')
.directive('canSave', function () {
return function (scope, element, attrs) {
var form = scope.$eval(attrs.canSave);
scope.$watch(function() {
return form.$dirty && form.$valid;
}, function(value) {
value = !!value;
attrs.$set('disabled', !value);
});
}
});
Plunker: http://plnkr.co/edit/0SyK8M
Plunker:http://plnkr.co/edit/0SyK8M
#2
2
You can pass the function call to the directive like this
您可以像这样将函数调用传递给指令
function Ctrl($scope) {
$scope.canSave = function () {
return form.$dirty && form.$valid;
};
}
app.directive('canSave', function () {
return {
scope: {
canSave: '&'
},
link: function (scope, element, attrs) {
attrs.$set('disabled', !scope.canSave());
}
}
});
This is the template
这是模板
<div ng-app="myApp" ng-controller="Ctrl">
<div can-save="canSave()">test</div>
</div>
You can see the function is called from the directive. Demo
您可以看到从指令调用该函数。演示
#1
3
angular.module('MyApp')
.directive('canSave', function () {
return function (scope, element, attrs) {
var form = scope.$eval(attrs.canSave);
scope.$watch(function() {
return form.$dirty && form.$valid;
}, function(value) {
value = !!value;
attrs.$set('disabled', !value);
});
}
});
Plunker: http://plnkr.co/edit/0SyK8M
Plunker:http://plnkr.co/edit/0SyK8M
#2
2
You can pass the function call to the directive like this
您可以像这样将函数调用传递给指令
function Ctrl($scope) {
$scope.canSave = function () {
return form.$dirty && form.$valid;
};
}
app.directive('canSave', function () {
return {
scope: {
canSave: '&'
},
link: function (scope, element, attrs) {
attrs.$set('disabled', !scope.canSave());
}
}
});
This is the template
这是模板
<div ng-app="myApp" ng-controller="Ctrl">
<div can-save="canSave()">test</div>
</div>
You can see the function is called from the directive. Demo
您可以看到从指令调用该函数。演示