Angularjs双向数据绑定推送对象从指令到控制器数组

时间:2016-06-10 11:51:45

标签: angularjs angularjs-directive

我在控制器中定义了一个数组,并使用双向绑定将其传递给指令。在指令中,我试图将对象推入该数组,但它失败了。

.controller("test", function($scope){
      $scope.myarr =[];

      $scope.$watch("myarr", function(newValue, oldValue){
         console.log($scope.myarr); //prints empty arr
     },true);
});

.directive('ptest', ['$compile', function($compile) {
    var object = {value: 'changed value'};
    return {
      restrict:"E"
      scope: {
            myarr:"="
      },
      template : "<div>{{iobj.value}}<div>",
      link: function(scope,elem,attr){
         myarr.push(object) ;
      }
    };
}]);

html

 <ptest myarr="myarr"></ptest>

2 个答案:

答案 0 :(得分:1)

尝试使用scope.myarr.push(object);代替myarr.push(object)

答案 1 :(得分:1)

@George Lee说试试scope.myarr.push(object);并且你的指令也有错误。在restrict:"E"之后,您忘记了,

 return {
  restrict:"E", // forgot put ','
  scope: {
        myarr:"="
  },
  template : "<div>{{iobj.value}}<div>",

// Code goes here

angular.module('app', [])

.controller("test", function($scope){
  $scope.myarr =[];

  
  $scope.$watch("myarr", function(newValue, oldValue){
    console.log($scope.myarr); //prints empty arr
  },true);
  
  $scope.addItem = function(){
      var object = {value: 'changed value2'};
       $scope.myarr.push(object);
    }
})

.directive('ptest', ['$compile', function($compile) {
  var object = {value: 'changed value'};
  return {
    restrict:"E",
    scope: {
      myarr:"="
    },
    template : '<div ng-repeat="item in myarr">{{item.value}}<div>',
    link: function(scope,elem,attr){
      scope.myarr.push(object) ;
    }
  };
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div  ng-app="app" ng-controller="test">
     <ptest myarr="myarr"></ptest>
     <input type="button" ng-click="addItem()" value="add">
  </div>