programing

$.param을 angularjs로 변환

elecom 2023. 10. 25. 22:35
반응형

$.param을 angularjs로 변환

JQuery를 사용하기 전에 매개변수를 사용하여 URL을 전송합니다.

window.location = myUrl + $.param({"paramName" : "ok","anotherParam":"hello"});

그러나 각진 jS에서는 동일한 방식으로 작동하지 않습니다.

$scope.myButton = function() {
    $window.location.open = myUrl + $.param({"paramName" : "ok","anotherParam":"hello"});
};//Error: $ is not defined

누가 angularJs에서 이것을 하는 방법을 도와줄 수 있습니까?

$.param(): $httpParamSerializer를 모방한 각도의 직렬화기가 내장되어 있습니다.제이큐라이크

$.param()이 하는 것처럼 데이터의 직렬 표현을 생성하려는 경우,

function serializeData( data ) { 
    // If this is not an object, defer to native stringification.
    if ( ! angular.isObject( data ) ) { 
        return( ( data == null ) ? "" : data.toString() ); 
    }

    var buffer = [];

    // Serialize each key in the object.
    for ( var name in data ) { 
        if ( ! data.hasOwnProperty( name ) ) { 
            continue; 
        }

        var value = data[ name ];

        buffer.push(
            encodeURIComponent( name ) + "=" + encodeURIComponent( ( value == null ) ? "" : value )
        ); 
    }

    // Serialize the buffer and clean it up for transportation.
    var source = buffer.join( "&" ).replace( /%20/g, "+" ); 
    return( source ); 
}

데이터 직렬화에 사용할 수 있습니다.

AngularJs는 코어에 jquery lite가 있으므로 $.param() 대신 angular.element.param()을 사용할 수 있습니다.

이 기능이 url serialization에 유용하다고 생각했습니다.중첩된 개체에도 적용됩니다.

var param = function(obj) {

  if ( ! angular.isObject( obj) ) { 
    return( ( obj== null ) ? "" : obj.toString() ); 
  }
  var query = '', name, value, fullSubName, subName, subValue, innerObj, i;

  for(name in obj) {

    value = obj[name];
    if(value instanceof Array) {
      for(i in value) {

        subValue = value[i];
        fullSubName = name + '[' + i + ']';
        innerObj = {};
        innerObj[fullSubName] = subValue;
        query += param(innerObj) + '&';
      }

    } else if(value instanceof Object) {
      for(subName in value) {

        subValue = value[subName];
        fullSubName = name + '[' + subName + ']';
        innerObj = {};
        innerObj[fullSubName] = subValue;
        query += param(innerObj) + '&';
      }
    }
    else if(value !== undefined && value !== null)
      query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
  }

  return query.length ? query.substr(0, query.length - 1) : query;
};

javascript 객체에서 $.param을 사용하여 $resource 또는 $http로 전달하면 됩니다.하지만 한 가지 주의해야 할 점은 배열이 아닌 개체라는 것입니다.

var badParam = {'name':'john',...}; // contains more properties
var goodParam = {name :'john',...}; // contains more properties

대신 이 함수를 주입하고 사용할 수 있습니다: $httpParamSerializerJQLike()

언급URL : https://stackoverflow.com/questions/24255195/convert-param-in-angularjs

반응형