3gwebtrain
3gwebtrain

Reputation: 15303

Not able to get the value from the `directive` scope

I am trying to get the value from ng-repeat directive, but only i am consoled by $index, the value consoles as undefiend.

what is wrong here?

my code :

HTML:

<body ng-controller="main">
     <h1>{{index}}</h1>

     <new-array index='$index' ng-repeat="value in values">{{value}}</new-array>
  </body>

JS:

var myApp = angular.module('myApp', []);

myApp.controller('main', function ($scope) {

  $scope.values = [{"name":"one", "num" : 1}, {"name":"two", "num" : 2}, {"name":"three", "num" : 3}]

  $scope.index = 0;

  $scope.update = function (num) {
    $scope.index = num;
  }

});

myApp.directive("newArray", function () {

  return {

    scope : {
      value : "=",
      index : "="
    },

    link : function (scope, element, attrs) {

      console.log(scope.value, scope.index)
      //reusult as "undefined" 1

    }

  }

})

Live Demo

Upvotes: 1

Views: 48

Answers (2)

zszep
zszep

Reputation: 4483

In your directive you are setting the scope to

  scope : {
      value : "=",
      index : "="
    }

This way you are creating an isolate scope that does not inherit from the parent scope. So you have to pass the value into the directive as "simoco" explained.

Upvotes: 0

Dmitry Pavliv
Dmitry Pavliv

Reputation: 35863

This

<new-array index='$index' ng-repeat="value in values">{{value}}</new-array>

should be

<new-array index='$index' value='value' ng-repeat="value in values">{{value}}</new-array>

Upvotes: 2

Related Questions