1

I have followed this url.Here I'm writing the data variable and assigning the data in the directive itself.

But I've json data in the separate sample.json file.Then how to get the sample.json data into the angular directive.Can anyone please help me out regarding this issue...

My js:

angular.module('myApp').directive('multiLine', [
  function() {
    return {
      restrict: 'E',
      scope: {
        data: '='
      },
      link: function(scope, element) {


var data = [
    {
        "City": "New York",
        "Data": [
            {
                "Date": "20111001",
                "Value": "63.4"
            },
            {
                "Date": "20111002",
                "Value": "58.0"
            },
            {
                "Date": "20111003",
                "Value": "53.3"
            }
        ]
    },
    {
        "City": "San Francisco",
        "Data": [
            {
                "Date": "20111001",
                "Value": "62.7"
            },
            {
                "Date": "20111002",
                "Value": "59.9"
            },
            {
                "Date": "20111003",
                "Value": "59.1"
            }
        ]
    },
    {
        "City": "Austin",
        "Data": [
            {
                "Date": "20111001",
                "Value": "72.2"
            },
            {
                "Date": "20111002",
                "Value": "67.7"
            },
            {
                "Date": "20111003",
                "Value": "69.4"
            }
        ]
    }
];

var margin = {
    top: 20,
    right: 80,
    bottom: 30,
    left: 50
},
width = 560 - margin.left - margin.right,
    height = 300 - margin.top - margin.bottom;

var parseDate = d3.time.format("%Y%m%d").parse;

var x = d3.time.scale()
    .range([0, width]);

var y = d3.scale.linear()
    .range([height, 0]);

var color = d3.scale.category10();

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left");

var line = d3.svg.line()
    .interpolate("basis")
    .x(function (d) {
    return x(d.Date);
})
    .y(function (d) {
    return y(d.Value);
});

var svg = d3.select(element[0]).append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

color.domain(data.map(function (d) { return d.City; }));

data.forEach(function (kv) {
    kv.Data.forEach(function (d) {
        d.Date = parseDate(d.Date);
    });
});

var cities = data;

var minX = d3.min(data, function (kv) { return d3.min(kv.Data, function (d) { return d.Date; }) });
var maxX = d3.max(data, function (kv) { return d3.max(kv.Data, function (d) { return d.Date; }) });
var minY = d3.min(data, function (kv) { return d3.min(kv.Data, function (d) { return d.Value; }) });
var maxY = d3.max(data, function (kv) { return d3.max(kv.Data, function (d) { return d.Value; }) });

x.domain([minX, maxX]);
y.domain([minY, maxY]);

svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);

svg.append("g")
    .attr("class", "y axis")
    .call(yAxis)
    .append("text")
    .attr("transform", "rotate(-90)")
    .attr("y", 6)
    .attr("dy", ".71em")
    .style("text-anchor", "end")
    .text("Temperature (ºF)");

var city = svg.selectAll(".city")
    .data(cities)
    .enter().append("g")
    .attr("class", "city");

city.append("path")
    .attr("class", "line")
    .attr("d", function (d) {
    return line(d.Data);
})
    .style("stroke", function (d) {
    return color(d.City);
});

city.append("text")
    .datum(function (d) {
    return {
        name: d.City,
        date: d.Data[d.Data.length - 1].Date,
        value: d.Data[d.Data.length - 1].Value
    };
})
    .attr("transform", function (d) {
    return "translate(" + x(d.date) + "," + y(d.value) + ")";
})
    .attr("x", 3)
    .attr("dy", ".35em")
    .text(function (d) {
        return d.name;
});
 }
    };
  }
]);

4 Answers 4

0

You can use $http for that. Example:

$http({method: 'GET', url:'path/to/file.json'})
    .then(
        function(json) {
            console.log('result: ', json);
        },
        function(error) {
            Console.warn('An error occured');
        }
    );

You can also use $http.get as a convenience function.

0

If you want to get the JSON Object from other file you can use the http Get Method as follows:

app.controller("testController", function($scope, $http) {
   $scope.data= [];
      $http.get('data.json').success(function(data) { 
         $scope.data = data.value;
         console.log(data.value);
      });    
});

Check this link : https://docs.angularjs.org/api/ng/service/$http

2
  • The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error. See: https://docs.angularjs.org/api/ng/service/$http#deprecation-notice Commented Feb 15, 2016 at 7:49
  • Oh okay. I didn't know about that the $http legacy promise methods success and error have been deprecated cause we still used it. Thanks for that useful information. Commented Feb 15, 2016 at 7:53
0

Inject $http into your directive:

angular.module('myApp').directive('multiLine', ['$http', function($http) {

Use it's get method to fetch the file:

$http.get('file.json').then(
    function resolved (response) {
        console.info('Resolved at ' + new Date());
        // response.data holds your JSON object
    },
    function rejected (response) {
        console.error('Rejected at ' + new Date());
    }
);

Reference: https://docs.angularjs.org/api/ng/service/$http#get

0
0
Here I created sample for how to get data from external json. 

Sample Link

myApp.factory('Data', ['$http', function($http) {
   var dataFactory = {};
    dataFactory.getdata = function () {
              return $http.get('your.json');
        };
    return dataFactory;
}]);

myApp.controller('FirstCtrl', function( $scope, Data ){
    Data.getdata().then(function (data) {
        $scope.Data = data.data;
  });
});

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.