初始角度模块值或来自$ .ajax响应的工厂

时间:2014-01-11 11:16:15

标签: javascript ajax angularjs

我将AngularJS实现到项目中。

angular.module('xmpl.service', []).
     value('objProduct', {
          productName: 'ASUS', // this fiel name and value set on angular start!!!!
          price: 0,            // this fiel name and value set on angular start!!!!
          func1: function (setObjProduct) {            
               this.productName = setObjProduct.productName;
               this.price = setObjProduct.price;                           
          },
          func2: function (name) {
               return this.productName + ' ' + name + '.';
          }
     }).
     value('objCustomer', {
          info: function (name) {
               this.name = name;
          }
     });
...
var myApp = angular.module('xmpl', ['xmpl.service', 'xmpl.directive', 'xmpl.filter']).
     run(function (objProduct, objCustomer) {            
            // I hope $.json request to MVC Controller in project will be here
            // Object from response go to func1 or func2

            // Some test object
            var newObjProduct = {
                productName: 'SAMSUNG',
                price: 400
            };            
            objProduct.func1(newObjProduct);
        });    

function XmplController($scope, objProduct, objCustomer) {                
        $scope.greeting = function (value) {
            return objCustomer.name + ' ' + value + ' ' + objProduct.productName;
        }

        $scope.varTest1 = objProduct.productName;

        $scope.varFuncTest = function () {
            return objProduct.price;            
        }        
    }

我尝试将$ .ajax请求发送到MVC Controller并从响应中获取一些对象。有没有办法从响应对象设置字段并设置名称和值而不是'productName'和'price'。在BLL中,所有对象都可以更改,我尝试从$ .ajax响应中获取一些对象并将其结构设置为angular。我该如何更改代码?

1 个答案:

答案 0 :(得分:0)

你可以这样做:

func1: function (setObjProduct) {
       for (var property in setObjProduct) {
           if (setObjProduct.hasOwnProperty(property)) {
               this[property] = setObjProduct[property];
           }
       }
   }          

这是标准的javascript,没有任何特定的角度。