范围属性可见性



首先,让我说我是AngularJS的新手,所以我的代码可能充满了反模式。如果是这样的话,请告诉我。

我正在使用angular-schema-formangular-translate来翻译我的标签。我已经验证了$translate服务返回的promise是否已正确解析,但由于某种原因,$scope.labels属性在promise之外不可见。

我知道这可能是我对Angular内部工作方式的误解,但我无法准确地理解我做错了什么。

这是控制器:

app = angular.module('myApp')
app.controller('SessionsController', ['$scope', '$translate',
  ($scope, $translate)->
    $scope.labels = []
    $translate(['models.user.labels.email', 'models.user.labels.password']).then(
      (translations)->
        $scope.labels = translations
    )
    # $scope.labels not visible here!
    $scope.loginFormSchema = {
      type: 'object',
      properties: {
        email: {
          type: 'string',
          title: $scope.labels['models.user.labels.email']
        },
        password: {
          type: 'string',
          title: $scope.labels['models.user.labels.password'],
          'x-schema-form': {
            type: 'password'
          }
        }
      },
      required: ['email', 'password']
    }
    $scope.loginForm = [
      '*',
      {
        type: 'submit',
        title: 'Sign in',
        style: 'btn btn-lg btn-primary'
      }
    ]
    $scope.login = {}
])

$translate是异步的。你可以这样做:

app = angular.module('myApp')
app.controller('SessionsController', ['$scope', '$translate',
  ($scope, $translate)->
    $scope.loginFormSchema = {
      type: 'object',
      properties: {
        email: {
          type: 'string'
        },
        password: {
          type: 'string',
          'x-schema-form': {
            type: 'password'
          }
        }
      },
      required: ['email', 'password']
    }
    $scope.loginForm = [
      '*',
      {
        type: 'submit',
        title: 'Sign in',
        style: 'btn btn-lg btn-primary'
      }
    ]
    $scope.login = {}
    $translate(['models.user.labels.email', 'models.user.labels.password']).then(
      (translations)->
        //$scope.labels = translations
        $scope.loginFormSchema.properties.email.title = translations['models.user.labels.email'];
        $scope.loginFormSchema.properties.password.title = translations['models.user.labels.password'];
    )
])

最新更新