1

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>

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Plunker attached: plnkr.co/edit/IhPxOnH3bBUBKojKMs98?p=preview Note: don't forget the comma after restrict:"E"
1

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>

1 Comment

I'll +1 this if you can figure out how to get the template to output value changed from the newly added value object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.