问题
I have
$scope.formTitle = '';
$scope.formDesc = '';
$scope.fields = [];
but would like to combine these into one $scope.theForm so I can have one object that would be easily converted into JSON.
What's the best way to do this?
回答1:
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: []
}
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.
回答2:
$scope.theForm = {
title: '',
desc: '',
fields: []
}
回答3:
I think what you want is something like this:
$scope.theForm = {
formTitle: '',
formDesc: '',
fields: []
}
Maybe instead of theForm you want to call it data or model or dataModel.
But you don't need to concretely define this on your scope if you are getting it from as a JSON object. In this example I won't use $scope either. I will use a resolve object to get the JSON object;
MyController.resolve = {
'myDataObject': ['myService', function(myservice] {
return myService.getMyDataObjectPromise();
}]
}
MyController.$inject = ['myDataObject'];
function MyController(myJsonObject) {
this.data = myJsonObject;
}
In your uiRouter or ngRouter you will point the resolve object for this controller as MyController.resolve. As well you will this example uses the controllerAs syntax. So with controller: 'MyController as vs' the view would access the data with vm.data.
来源:https://stackoverflow.com/questions/27488920/how-can-i-combine-multiple-scope-models-in-angular