0
$scope.results = [
    {id: 1, text: 'a'},
    {id: 2, text: 'b'},
    {id: 3, text: 'c'},
    {id: 4, text: 'd'}
];
<label ng-repeat="result in results">
    <input type="checkbox" name="res" data-checklist-model="my.resid" data-checklist-value="result.id" ng-click="myFunction(result.id)" > {{result.text}}
</label>
$scope.myFunction = function(id){
    $scope.dflt = [];
    if($scope.my.resid == 1){
        $scope.dflt.push({"id": 1, "text": 'a'});
        console.log($scope.dflt);
    }
}

I want to append dynamically as i expected result below but for now it is just showing [{"id":1,"text":"a"}]

[{"id":1,"text":"a"}, {"id":2,"text":"b"}, {"id":3,"text":"c"}, {"id":4,"text":"d"}]
1
  • On every click, $scope.dflt is initialized again...Make it global in controller... Commented Jul 4, 2016 at 12:21

3 Answers 3

2

On every click, $scope.dflt is initialized again...Make it global in controller.

var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", function($scope) {
  $scope.results = [{
    id: 1,
    text: 'a'
  }, {
    id: 2,
    text: 'b'
  }, {
    id: 3,
    text: 'c'
  }, {
    id: 4,
    text: 'd'
  }];
  $scope.dflt = [];
  $scope.myFunction = function(obj) {
    $scope.dflt.push(obj);
    console.log($scope.dflt);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <label ng-repeat="result in results">
    <input type="checkbox" name="res" data-checklist-model="my.resid" data-checklist-value="result.id" ng-click="myFunction(result)">{{result.id}}
  </label>
</div>

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

3 Comments

it is not appending the value it should append [{"id":1,"text":"a"}, {"id":2,"text":"b"}]
@Jimmy, Then what is being appended ? Read about $$hashKey
sry Rayon i haven't checked it
0
$scope.results = [
    {id: 1, text: 'a'},
    {id: 2, text: 'b'},
    {id: 3, text: 'c'},
    {id: 4, text: 'd'}
  ];


 <label ng-repeat="result in results">
                <input type="checkbox" name="res" data-checklist-model="my.resid" data-checklist-value="result.id" ng-click="myFunction(result.id)" > {{result.text}}
              </label>


$scope.myFunction = function(id){

     $scope.dflt = $scope.dflt || [];

          if($scope.my.resid == 1){
            $scope.dflt.push({"id": 1, "text": 'a'});
    console.log($scope.dflt);
          }

}

Comments

0

Make $scope.dflt outside of the currrent function and it would work. You are overwriting the array to empty every time you perform a click

Comments

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.