How can I combine multiple scope models in Angular?

雨燕双飞 提交于 2019-12-24 14:14:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!