Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

I have a array defined in controller and passing it to directive using two way binding. In directive, i tried to pushed object into that array but it failed.

.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>
share|improve this question

Try scope.myarr.push(object); instead of myarr.push(object)

share|improve this answer
    
Plunker attached: plnkr.co/edit/IhPxOnH3bBUBKojKMs98?p=preview Note: don't forget the comma after restrict:"E" – Raphael Rafatpanah Jun 10 at 12:18

as @George Lee said try scope.myarr.push(object); and also your directive have a mistake. after restrict:"E" you forgot put ,

 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>

share|improve this answer
    
I'll +1 this if you can figure out how to get the template to output value changed from the newly added value object. – Raphael Rafatpanah Jun 10 at 12:38
1  
@RaphaelRafatpanah see updated answer. – SSH Jun 10 at 12:48

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.