Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/434.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 是否可以为角度模型属性名称创建映射?_Javascript_Angularjs_Angularjs Ng Repeat_Restangular - Fatal编程技术网

Javascript 是否可以为角度模型属性名称创建映射?

Javascript 是否可以为角度模型属性名称创建映射?,javascript,angularjs,angularjs-ng-repeat,restangular,Javascript,Angularjs,Angularjs Ng Repeat,Restangular,我目前正在开发一个数据库模式经常更改的应用程序。这种快速变化给我的前端Angular代码带来了一个大问题,它通过Restangular使用后端JSONAPI(我没有太多控制权);以以下代码为例: <ul> <li ng-repeat="item in items"> <h2>{{item.label}}</h2> </li> </ul> 然后,下次当“item_标签”更改为其他内容时,我可以

我目前正在开发一个数据库模式经常更改的应用程序。这种快速变化给我的前端Angular代码带来了一个大问题,它通过Restangular使用后端JSONAPI(我没有太多控制权);以以下代码为例:

<ul>
    <li ng-repeat="item in items">
        <h2>{{item.label}}</h2>
    </li>
</ul>
然后,下次当“item_标签”更改为其他内容时,我可以在这个配置对象中更新它,而不用担心模板中的所有引用


谢谢。

angular的理念是,你可以用这个模型做任何你想做的事情。虽然这并没有为您指明任何具体的方向,但它确实为您提供了以自己的OO方式实现它的机会。假设您有一个应用程序,其中有一个名为…
Task
的数据对象,任务模型可能如下所示

function Task(initJson){
    this.name = initJson._name || 'New Task';
    this.completed = initJson.is_completed || false;
    this.doneDateTime = initJson.datetime || null;        
}

Task.prototype = {
    save: function(){
        //do stuff with this and $http.put/post...        
    }
    create: function(){
        //do stuff with this and $http.put/post
    }
    //....etc
}
所有这些都可能被包装在一个工厂里

myApp.factory('TaskFactory',function($http){
    var Tasks = []; //Or {};

    //above constructor function...
    //other helper methods...etc



    return {
        instance: Task,
        collection: Tasks,            
        init: function(){} // get all tasks? run them through the constructor (Task), populate collection
    };
})

然后,您可以编辑构造函数上的属性(一个位置(对于每个数据类型),唯一的位置)。虽然如果您使用诸如Restangular或$resource之类的东西,这并不理想,因为它们不具备作为大型备份存储的能力,但它们只是假设了跨线的属性,这对于大型、不断变化的应用程序来说,有时很难管理

我最终使用了restanglar的
setResponseExtractor
config属性

看起来是这样的:

Restangular.setResponseExtractor(function(response, operation, what, url) {
    var newResponse = response;
    angular.forEach(newResponse.items, function(item) {
        item.label = item.item_label;
    }
    return newResponse;
}

非常感谢,卡勒博伊德!这听起来确实是一个很好的解决方案。但是,正如您上面提到的,对于大型项目来说,它并不理想。请看我最后给出的解决方案的答案。
Restangular.setResponseExtractor(function(response, operation, what, url) {
    var newResponse = response;
    angular.forEach(newResponse.items, function(item) {
        item.label = item.item_label;
    }
    return newResponse;
}