【问题标题】:AngularJS - How to get angular object from 'this'AngularJS - 如何从“this”获取角度对象
【发布时间】:2018-04-09 21:30:25
【问题描述】:

我是 Angular 的新手,也许我错过了一些概念。我的想法是将 Angular 控制器逻辑与 UI 逻辑分开,这意味着控制器可以很容易地重用,而无需知道 UI 将如何处理它处理的数据。在这种情况下,例如,我想清除控制器外部的表单和输入错误。

想象一下,我有一个这样的控制器功能:

    $scope.createCategory = function () {
    $scope.Loading = true;
    $scope.clearServerError();
    $scope.categoryForm.$setPristine();
    angular.forEach($scope.categoryForm, function (input) {
        if (input && input.hasOwnProperty('$viewValue')) {
            input.$setPristine();
            input.$setUntouched();
        }
    });

    $("#categoryForm :input").prop("disabled", true);

        var response = $http({
            url: "/api/categories",
            method: "POST",
            headers: authHeaders,
            data: JSON.stringify($scope.NewCategory),
        }).then(function mySuccess(response) {
            $scope.Categories.push(response.data);
            $scope.resetNewCategory();
            $('#category-add-modal').modal('hide');
        }, function myError(response) {
            var message = response.data.error_description;

            $scope.Server.error = true;
            $scope.Server.message = message;
        }).finally(function end() {
            $scope.Loading = false;
            $("#categoryForm :input").prop("disabled", false);
        });
};

如您所见,控制器现在包含 UI 的某些方面,例如表单名为“categoryForm”,还有一个名为“#category-add-modal”的模式。我想分离这个逻辑,传递 4 个函数回调:initCallback、successCallback、failureCallback 和 finallyCallback。只有这三个函数会知道 UI 有哪些元素。在这种情况下,例如,initCallback 应该将类别表单和所有输入重置为 Pristine 并且保持不变。这如何实现?

【问题讨论】:

  • 通常,$http 部分将存在于service 中,并被注入controller
  • 我明白了。我一定会遵守你的规则。所以这意味着我将为每个 UI 都有一个新的控制器?

标签: angularjs


【解决方案1】:

您通常不需要在 Angular 控制器中使用 JQuery。例如

$("#categoryForm :input").prop("disabled", true);

可以使用ng-disabled 属性重写,这将是一种干净的方式。

【讨论】:

  • 我是新人,你在写。我可以将它与作用域上的 Loading 变量一起使用。
  • 这可行。对于模态对话框,调用 jquery 是可以的,还有一个选项可以使用 angular 指令进行引导(更多 here)。
  • 是的,我按照您的建议做了并解决了部分问题。仍然无法分离模态逻辑并设置原始和原样。你有什么建议吗?
  • setPristinesetUntouched 都使用表单名称,例如 $scope.formName.$setUntouched()。如果以这种方式使用,似乎不需要遍历输入控件。
猜你喜欢
  • 2023-02-06
  • 1970-01-01
  • 2021-02-03
  • 2021-07-22
  • 2021-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多