FIDDLE
I have created a directive :-
return {
restrict: \'EAC\',
scope: {
statesActive: \'=\'
},
inject $parse in your directive.... try this...
angular.module('myApp').directive('gtMap', ['$parse',
function($parse) {
return {
restrict: 'EAC',
link: function (scope, element, attrs) {
var fieldGetter = $parse(attrs.statesActive);
console.log(fieldGetter)
var field = fieldGetter(scope);
//var stateData = scope.statesActive.states;
// Don't get data here
console.log(field)
}
}
}
]);
return {
restrict: 'EAC',
scope: {
statesActive: '='
},
link: function (scope, element, attrs) {
var stateData = angular.fromJson(attrs.statesActive).states; // Probably, your "states" model here
....
}
You have mistakes in $scope.states
. It must be an object, not a string.
Following code works
JS
angular.module('myApp', []);
angular.module('myApp').directive('gtMap',
function() {
return {
restrict: 'EAC',
scope: {
statesActive: '='
},
link: function (scope, element, attrs) {
var stateData = scope.statesActive.states;
// Don't get data here
console.log(scope.statesActive);
}
}
}
);
angular.module('myApp').controller('MyCtrl',
function($scope) {
// If states is a string got from database, use angular.fromJson(json) to parse.
// $scope.states = angular.fromJson(response);
$scope.states = {states:[{ 'state' : 'CA', 'color' : '#61c419'}]};
});
HTML
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<gt-map states-active="states"></gt-map>
</div>
</div>
Check out this jsfiddle http://jsfiddle.net/fizerkhan/69Pq9/1/
scope.statesActive
is an array so you need to access it as follows
var stateData = scope.statesActive[0].states;
A slight tweak to the fiddle was referenced in a comment to another answer that now shows the retrieval of states within the directive's link function via its scope:
link: function (scope, element, attrs) {
var stateData = $parse(scope.statesActive)();
console.log(stateData);
}
by stating:
scope: { statesActive: '=' }
you are binding your directive's scope to the attribute named states-active
so all you have to do reference it inside the directive is to use
scope.statesActive
this will get the value as a string, you can use the $parse service to get the value of your object
Try using this to access your scope.
return {
...
link: function (scope, element, attrs) {
....
scope.$parent.$parent.YourVariable;
}
};
And I think you need to change your HTML to this:
<gt-map states-active="states"></gt-map>