如何在AngularJS中创建动态对象?

时间:2016-08-28 07:23:30

标签: javascript html angularjs

我有这段代码

  <script>
      var demo =angular.module('ExampleApp', ['ngDraggable']);
      demo.controller('MainCtrl', function ($scope) {
          $scope.centerAnchor = true;
          $scope.toggleCenterAnchor = function () {$scope.centerAnchor = !$scope.centerAnchor}
          $scope.draggableObjects = [{name:'subject1'}, {name:'subject2'}, {name:'subject3'}];
          $scope.droppedObjects1 = [];
          $scope.droppedObjects2 = [];
          $scope.onDropComplete1=function(data,evt,i){
              console.log(data);
              var index = $scope["droppedObjects"+i].indexOf(data);
              if (index == -1)
                  $scope["droppedObjects"+i].push(data);
          }
          $scope.onDragSuccess1=function(data,evt,i){
              console.log("133","$scope","onDragSuccess1", "", evt);
              var index = $scope["droppedObjects"+i].indexOf(data);
              if (index > -1) {
                  $scope["droppedObjects"+i].splice(index, 1);
              }
          }
        var inArray = function(array, obj) {
            var index = array.indexOf(obj);
        }
      });
      var x = 1;
      demo.$inject = ['$scope'];

      demo.directive("boxCreator", function($compile){
          return{
              restrict: 'A',
              link: function(scope , element){
                  element.bind("click", function(e) {

                      var childNode = $compile('<div ng-drop="true" ng-drop-success="onDropComplete1($data,$event,'+x+')"><span class="title">Drop area #'+x+'</span><div ng-repeat="obj in droppedObjects'+x+'" ng-drag="true" ng-drag-data="obj" ng-drag-success="onDragSuccess1($data,$event,x)" ng-center-anchor="{{centerAnchor}}">{{obj.name}}</div></div>')(scope)
                      element.parent().prepend(childNode);
                      x++;
//                      console.log(angular.element('ng-drop'));
                  });
              }
          }
      });
  </script>

我尝试做的是点击按钮而不是$scope.droppedObjects1 = [];而动态创建对象,$scope.droppedObjects2 = [];请帮助我解决这个问题以及代码中需要进一步更改的内容。我是AngularJS的新手。

1 个答案:

答案 0 :(得分:0)

解决方案是使用$ parse var the_string =&#39; new_scope&#39;;

//获取模型 var model = $ parse(the_string);

//为其指定一个值 model.assign($ scope,07);

的console.log($ scope.new_scope);