重置表单中的组件值

时间:2017-09-25 18:19:58

标签: angularjs

我有一个组件,它在其控制器$ postLink事件中使用从ajax请求获得的值进行初始化。该组件位于表单中。

然后用户可以更改默认值然后提交。提交表单时,组件值变为空白。我需要找到一种方法来重新初始化从ajax请求获得的值,但当然$ postLink事件不能再次触发,因为已经创建了组件。

组件js:

app.component('formFieldPortafoglioSelector', {
    templateUrl: 'ngComponents/form-field-portafoglio-selector.html',
    bindings: {
        label: '@',
        model: '='
    },
    controller: ['$scope', 'ApiService', function($scope, ApiService) {
        var ctrl = this;

        ctrl.$postLink = function() {
            ApiService.domini.then(function(response) {
                $scope.portafogli = response.domini.portafogli;
                ctrl.model = $scope.portafogli[0].id_ptf;
            });
        };
    }]
});

组件模板:

<div class="form-group">
    <label class="col-form-label col-form-label-sm">{{ $ctrl.label }}</label>
    <select class="form-control custom-select"
            ng-options="ptf.id_ptf as ptf.des_ptf for ptf in portafogli"
            ng-model="$ctrl.model"
            >
    </select>
</div>

组件使用:

<div ng-controller="resourceController as rc">
    <form ng-submit="rc.operazione.$save()">
        <form-field-portafoglio-selector model="rc.operazione.id_ptf_sorgente" label="Portafoglio Sorgente">
        </form-field-portafoglio-selector>
    </form>
</div>

资源控制器的定义如下:

app.controller('resourceController', ['$scope', '$resource', function($scope, $resource) {
    this.operazione = new $resource('operazioni', null, {})();
}]);

0 个答案:

没有答案