将元素推送到用户指定对象的数组中

时间:2014-02-07 06:05:41

标签: javascript angularjs

我正在尝试手动指定对象'data1.authNames'&来自html的'data2.authNames'并尝试将对象推送到它上面。我得到'不能调用方法'推'未定义'哪里出错了?

HTML

<body ng-controller="MainCtrl">
    <button ng-click="setAuthName('data1.authNames')">Button1</button>
    <button ng-click="setAuthName('data2.authNames')">Button2</button>
</body>

JS

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.data1 =  $scope.data2 = {};
  $scope.data1.authNames = [];
  $scope.data2.authNames = [];

  $scope.setAuthName = function(obj){
    $scope.obj.push("Hello");
  }

});

演示:http://plnkr.co/edit/xJ42UxQBVYYyFg8ljLDu?p=preview

1 个答案:

答案 0 :(得分:1)

这样做:

$scope.setAuthName = function(obj){
    getProp($scope, obj).push("Hello");
};

function getProp(obj, prop){
    var parts = prop.split('.');
    var _ref = obj;
    for(var i = 0; i < parts.length; i++){
        var part = parts[i];
        if(i === parts.length - 1)
            return _ref[part];
        else
            _ref = _ref[part] || {};
    }
}

编辑:你还有其他错误,请看一下:

app.controller('MainCtrl', function($scope) {
  $scope.data1 = { authNames: [] };
  $scope.data2 = { authNames: [] };

  $scope.setAuthName = function(obj){
    var o = getProp($scope, obj);
    o.push("Hello");
    console.log(o);
  }

  function getProp(obj, prop){
    var parts = prop.split('.');
    var _ref = obj;
    for(var i = 0; i < parts.length; i++){
        var part = parts[i];
        if(i === parts.length - 1)
            return _ref[part];
        else
            _ref = _ref[part] || {};
    }
  }
});