AngularJS 输入未使用 ng-model 更新

AngularJS input not updating with ng-model

我有一个包含三个输入字段的表单:

<form name="myForm" novalidate ng-controller="MainController as vm">
    <div>
        <input type="text" ng-model="vm.id" name="idInput" required>
        <input type="email" ng-model="vm.email" name="emailInput" required>
        <input type="text" ng-model="vm.output" name="output">
    </div>
</form>

vm.output 是在我的控制器中定义的一个变量,它包含一些字符串加上 vm.idvm.email:

vm.output = 'myurl.com?id=' + vm.id + '&email=' + vm.email;

我想根据用户在 ID 和电子邮件字段中的输入生成输出 URL。但是,当我在其他两个字段中输入一些内容时,输出字段不会更新。它只是说 myurl.com?id=undefined&email=undefined,

如果我使用

我可以让它工作

ng-value="'myurl.com?id=' + vm.id + '&email=' + vm.email"

但是,我正在使用 ng-clip,它通过使用 ng-model 获取要复制的内容,所以我需要使用它。

此外,这是我的控制器:

angular
    .module("app")
    .controller("MainController",[MainController);

function MainController(){
    var vm = this;

    vm.output = 'myurl.com?id=' + vm.id + '&email=' + vm.email;
}

有什么建议吗?

您可以通过几种不同的方式完成此操作。一种方法是在您要观看的每个输入上设置 ng-change 事件:

<div>
    <input type="text" ng-model="vm.id" ng-change="updateOutput()" name="idInput" required />
    <input type="email" ng-model="vm.email" ng-change="updateOutput()" name="emailInput" required />
    <input type="text" ng-model="vm.output" name="output" />
</div>

然后,您必须在控制器作用域上构建 update 方法:

app.controller = app.controller('MainController', function($scope) {

    $scope.vm = {
      output: '',
      email: '',
      id: ''
    };

    $scope.updateOutput = function() {
      $scope.vm.output = 'myurl.com?id=' + $scope.vm.id + '&email=' + $scope.vm.email;
    }
});

这里是working plunker.

我会使用可以正确设置模型值的自定义指令:

app.directive('concatModel', function($parse) {

    var pattern = function(data) {
        return 'myurl.com?id=' + data.id + '&email=' + data.email;
    };

    return {
        require: 'ngModel',
        scope: {
            data: '=concatModel'
        },
        link: function(scope, element, attrs, controller) {
            scope.$watchCollection('data', function(newVal) {
                controller.$setViewValue(pattern(newVal));
                controller.$render();
            });
        }    
    };
});

并像这样使用它:

<div>
    <input type="text" ng-model="vm.id" name="idInput" required="" />
    <input type="email" ng-model="vm.email" name="emailInput" required="" />
    <input type="text" concat-model="{id: vm.id, email: vm.email}" ng-model="vm.output" name="output" />
</div>

演示: http://plnkr.co/edit/sFW16LLZK3TezNAvYk5F?p=info