簡體   English   中英

使用vm作為控制器時如何設置輸入字段的初始值?

[英]How to set initial value of input field when using vm as controller?

我正在使用john papa風格來開發我的角度應用程序,因此有控制器將數據傳遞給使用服務的另一個控制器。 在第二個控制器中,我想在控制器被調用時設置輸入字段的值。 我試圖將其設置為

vm.form.mobile = getMob [1] .mobile;

但這對我沒有用。

這是我的第二位控制器

 (function ()
    {
        'use strict';

        angular
            .module('app.pages.auth.verify-mobile')
            .controller('VerifyMobileController', VerifyMobileController);

        /** @ngInject */
        function VerifyMobileController($scope,dataservice,msApi, $state,$mdDialog)
        {
            var vm = this;
            window.onbeforeunload = function() {
                $state.go('app.pages_auth_login');
            }
            var getMob = dataservice.getData();
            if(typeof getMob !== 'undefined'){

               vm.form.mobile = getMob[1].mobile;

            }
}
}();

這是html元素

<form name="verifyMobileForm" novalidate>
                <md-input-container class="md-block" md-no-float>
                    <input type="mobile" id="mobile" name="mobile" ng-model="vm.form.mobile" placeholder="Your Mobile number" ng-pattern="/^[789]\d{9}$/" maxlength="10" required>
                    <div ng-messages="verifyMobileForm.mobile.$error" role="alert" multiple>
                        <div ng-message="required">
                            <span >Mobile no. is required</span>
                        </div>

                    </div>

                </md-input-container>
                <div class="dialog-demo-content" layout="row" layout-wrap layout-margin layout-align="center">
                    <md-button type="submit" class="md-raised md-accent submit-button" ng-disabled="verifyMobileForm.$invalid || verifyMobileForm.$pristine" ng-click = "vm.checkMobile($event, document.getElementById('mobile').value)">
                        Next
                    </md-button>
                </div>
            </form>

嘗試添加ng-value屬性ng-value =“ {{vm.form.mobile}}”“

例如:

<input type="mobile" id="mobile" name="mobile" ng-value="{{vm.form.mobile}}" ng-model="vm.form.mobile" placeholder="Your Mobile number" ng-pattern="/^[789]\d{9}$/" maxlength="10" required>

確保在視圖中使用controllerAs語法,如下所示:

<div ng-controller="VerifyMobileController as vm">

編輯:順便說一句

 if(typeof getMob !== 'undefined')

當結果返回為null或NaN時,有一天可能會用腳射擊您,更常見的寫法是:

if(getMob)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM