AngularJS Controller在模板加载之前执行

时间:2014-11-05 02:56:29

标签: javascript angularjs

我有一个电子邮件验证链接,看起来像

 .when('/user/register/verify/:verify_code?', {
      controller: 'AngularRegisterVerifyPage',
      templateUrl: '/user/register/verify'
 })

我的输入字段就是这样。

input(ng-model="formData.verify_code", name="verify_code", type='text', class='form-control', placeholder='Verification Code', id="verify_code")

此模板应在模板加载时将参数插入文本字段

 document.getElementById('verify_code').value = "Test"; // Debugging Test Code
 $scope.formSubmitted = false;
 if ($routeParams.hasOwnProperty("verify_code")) {
      document.getElementById('verify_code').value = $routeParams.verify_code;
 }

但似乎控制器在模板实际加载之前执行此操作,因为当页面加载输入字段为空时。有关如何正确执行此操作的任何信息都很棒,我尝试使用Google搜索“加载控制器后加载模板”之类的内容但没有找到任何内容。感谢。

编辑:

我尝试将ng-init="loadCode()"添加到输入字段,但它仍无效。

 $scope.loadCode = function() {
      if ($routeParams.hasOwnProperty("verify_code")) {
           console.log('Called');
           document.getElementById('verify_code').value = $routeParams.verify_code;
           console.log($routeParams.verify_code);
           console.log(document.getElementById('verify_code').value);
      }
 }

1 个答案:

答案 0 :(得分:0)

您无需在angularjs中通过manupulate dom更改输入值。 Angular已经有很多巨大的机制来帮助您减少开发工作。

在您的情况下,您只需将代码更改为:

.controller('AngularRegisterVerifyPage', function($scope, $routeParams){
     $scope.formData = {};
     if ($routeParams.hasOwnProperty("verify_code")) {
         //You change your value in your model, angular will render this to your html(view)
         $scope.formData.verify_code = $routeParams.verify_code;
     }

});

以下是角度较新的有用答案:“Thinking in AngularJS” if I have a jQuery background?

Here is ngModel Document.

享受它:)