【问题标题】:Better way to refactor $scope operations like this in AngularJS?在 AngularJS 中重构像这样的 $scope 操作的更好方法?
【发布时间】:2015-02-12 16:00:46
【问题描述】:

我的咖啡脚本代码如下所示

.controller('SignInController',
    ($scope, CONFIG, restAuth, cookieAuth) ->
        $scope.signInData = {}
        $scope.res = {}
        # TODO: Refactor this to service

        $scope.processRegistration = ->
            console.log($scope.signInData)
            restAuth.post('signin', $scope.signInData)
            .then(((data) ->
                    if data.res >= 0
                        $scope.res.signInSuccess = true
                        $scope.res.msg = 'You finished login successfully.'
                        cookieAuth.setCookie(data)
                    else
                        $scope.res.signInSuccess = false
                        $scope.res.msg = 'Your login failed. (#{ data.description })'
                ),
                (->
                    $scope.res.signInSuccess = false
                    $scope.res.msg = 'Sorry, it seems that the server is not responding. Please try again later!')
            )


        return
)

.controller('SignUpController',
    ($scope, $http, CONFIG) ->
        $scope.signUpData = {}
        $scope.res = {}
        # TODO: Refactor this to service

        $scope.processRegistration = ->
            $http
            .post('#{ CONFIG.ROOT }/auth/signup', $scope.signUpData)
            .success (data) ->
                if data.res >= 0
                    $scope.res.signUpSuccess = true
                    $scope.res.msg = 'You finished registration successfully.'
                else
                    $scope.res.signUpSuccess = false
                    $scope.res.msg = 'Your registration failed. (#{ data.description })'
            .error(->
                $scope.res.signUpSuccess = false
                $scope.res.msg = 'Sorry, it seems that the server is not responding. Please try again later!'
            )

        return
)

可以看到,$scope上的操作很多,看起来有点笨拙。。有没有人有关于如何重构这个的建议?

【问题讨论】:

  • 将它们放入服务中。如果您在 html 中使用该函数,可能所有范围函数都会调用服务函数。

标签: javascript angularjs coffeescript


【解决方案1】:

我遵循 John Papa 风格指南,他建议使用带有 $scope 的经典控制器的 controllerAs 语法。以下是他的陈述:

在带有 $scope 的经典控制器上使用 controllerAs 语法 语法。

controllerAs 语法在被绑定的控制器内部使用 this 到 $scope

为什么?:controllerAs 是 $scope 上的语法糖。你仍然可以绑定 到 View 并且仍然可以访问 $scope 方法。

Why?:有助于避免在 a 中使用 $scope 方法的诱惑 控制器,否则可能会更好地避开它们或移动它们 到工厂。考虑在工厂中使用 $scope,或者如果在 控制器仅在需要时。例如在发布和 使用 $emit、$broadcast 或 $on 订阅事件考虑移动 这些使用到工厂并从控制器调用。

您可以在此处找到完整的指南: https://github.com/johnpapa/angularjs-styleguide

【讨论】:

    猜你喜欢
    • 2015-10-24
    • 1970-01-01
    • 2017-08-21
    • 2010-09-13
    • 2010-09-05
    • 2021-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多