我的应用程序没有正确绑定AngularJS

时间:2015-04-13 19:02:28

标签: javascript angularjs

我正在尝试使用Angular完成此应用程序,但有些东西不能正常工作。

我有这个控制器:

app.controller('GetStartedCtrl', ['$scope', '$rootScope', '$state', '$location', function ($scope, $rootScope, $state, $location) {

    var data = $location.search();
    $location.search({});

    $scope.years = [];
    $scope.months = [
        {value: '01', name: 'January'},
        {value: '02', name: 'February'},
        {value: '03', name: 'March'},
        {value: '04', name: 'April'},
        {value: '05', name: 'May'},
        {value: '06', name: 'June'},
        {value: '07', name: 'July'},
        {value: '08', name: 'August'},
        {value: '09', name: 'September'},
        {value: '10', name: 'October'},
        {value: '11', name: 'November'},
        {value: '12', name: 'December'}
    ];
    $scope.currentQuestion = 1;
    $scope.form = {};
    $scope.form.zipcode = 12345;

}]);

然后我在模板中有这个HTML:

<div class="questionnaire">
    <form name="questionnaire" id="questionnaire" novalidate="true" ng-submit="submitForm()">
        <div class="question1 question" ng-class="{ 'overlay': currentQuestion > 1 }" ng-show="currentQuestion >= 1">
            <p>Saving money doesn't have to be work. Let's keep it simple.</p>
            <span>Enter Your Zip</span><input type="text" name="zipcode" ng-model="form.zipcode" required="true" ng-pattern="/^\d{{5}}(-\d{{4}})?$/" />
        </div>
        <div class="question2 question" ng-class="{ 'overlay': currentQuestion > 2 }" ng-show="currentQuestion >= 2">
            <p>Ok. You're located in {{city}}, {{state}}. We hope you're experiencing good weather there.</p>
            <span>Are You:</span><i>(check one)</i><br/><br/>
            <input type="radio" name="type" id="business" value="business" /><label for="business" ng-model="form.type"><span></span>Business</label><br/>
            <input type="radio" name="type" id="residential" value="residential" /><label for="residential" ng-model="form.type"><span></span>Residential</label>
        </div>
        <pre>{{form}}</pre>
    </form>
</div>

所以发生的事情是我将$scope.form.zipcode属性设置为12345并且它正确地应用于输入字段,但不适用于在页面底部转储的表单属性:

Zip Code box displaying correctly

奇怪的是,如果我将zipcode输入上的绑定更改为不同的内容,则底部的转储显示正确,但邮政编码框无法填写:

enter image description here

有没有人知道为什么会发生这种情况以及我如何修复它以便正确设置绑定?基本上需要发生的是,应填写邮政编码盒,底部的转储应具有正确的zipcode属性。

如果有任何我需要澄清的内容,请告诉我。

谢谢! 布兰登

1 个答案:

答案 0 :(得分:1)

我认为问题在于ng-pattern没有匹配,并且它不允许你的值进入对象。

删除@ Matthew Green提到的额外花括号

最后

更改您的正则表达式
ng-pattern="/^\d{{5}}(-\d{{4}})?$/"

ng-pattern="/^\d{5}(-\d{4})?$/"

或不要使用周围的双引号

 ng-pattern=/^\d{5}(-\d{{4}})?$/