How to isolate async validity checks from controller to directive to solve DRY and isolated scope issues?

自闭症网瘾萝莉.ら 提交于 2020-02-25 04:44:05

问题


I find myself often repeating the following code in multiple controllers, one for each business object:

$scope.original = {name:"John"};
$scope.status = {error:false};

$scope.editMode = false;
$scope.cancel = function() {
    $scope.item = angular.copy($scope.original);
    $scope.editMode = false;
};
$scope.edit = function() {
    $scope.editMode = true;
};
$scope.item = angular.copy($scope.original);
$scope.save = function(item) {
    // do something ajax here
    // if it comes back 409, mark as conflict
    if ($scope.status.error) {
        $scope.myForm.name.$setValidity("conflict",false);
    } else {
        $scope.original = angular.copy($scope.item);
        $scope.editMode = false;
    }
};

The problems are several:

  1. The above is boilerplate that gets repeated for each business object that a user can edit, which creates lots of repetition.
  2. I cannot guarantee that $scope.myForm is accessible from the $scope, especially as other directives may have created isolated scopes around the form or input elements
  3. Playing with the validity from within the controller seems unnatural. I get that I need to do my resource.$save() or other $http activity from within the controller, but it feels like this type of direct validity setting belongs in a directive.
  4. Directly setting the validity means that I also need to actively watch for when it is no longer invalid. In my example fiddle (below), if you set it invalid, then cancel and edit again, it remains invalid. http://jsfiddle.net/shp0e10q/2/

来源:https://stackoverflow.com/questions/25974097/how-to-isolate-async-validity-checks-from-controller-to-directive-to-solve-dry-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!