本文介绍了如何在 Angular 中组合多个范围模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有

    $scope.formTitle = '';
    $scope.formDesc = '';
    $scope.fields = [];

但想将这些组合成一个 $scope.theForm 以便我可以拥有一个可以轻松转换为 JSON 的对象.

but would like to combine these into one $scope.theForm so I can have one object that would be easily converted into JSON.

最好的方法是什么?

推荐答案

没有什么能阻止您在包装类中托管您的属性.对于目的相似的属性(例如表单属性),它实际上是一种推荐的方法.

Nothing is stopping you from hosting your properties in a wrapping class. It is actually a recommended approach to use for the properties that are similar in purpose (like form properties for example).

// create wrapping class
$scope.theForm = {};

// add properties to the class
$scope.theForm.formTitle = '';
$scope.theForm.formDesc = '';
$scope.theForm.fields = [];

或者你可以在同一个语句中声明属性,就像这样

or you can declare the properties in the same statement, like this

$scope.theForm = {
    title: '',
    desc: '',
    fields: []
}

HTML和其他任何地方,您只需使用包装类名称作为前缀来访问这些属性:theForm.formTitleng-repeat="field in theForm.fields"

In HTML, and everywhere else, you simply access these properties using the wrapping class name as prefix: theForm.formTitle, ng-repeat="field in theForm.fields", etc.

这篇关于如何在 Angular 中组合多个范围模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 04:53