angular.js - AngularJS requests Json and assigns it to the directive
仅有的幸福
仅有的幸福 2017-05-15 17:01:52
0
4
677

I am using the following method to draw pictures with D3.js in angular. The first part is to implement the drawing function. It involves writing instructions in directive.js, writing scope in controller.js, and writing the three parts of the instruction in the page. My problem is: when I put the scope value in controller.js into json and access it, I cannot draw the same graph.
First, paste the code that can realize the drawing function, but the scope value is written locally:
1. directive.js


2. controller.js

3. left.html

The above method can draw the picture of angular d3.js, as follows~

But here comes the problem. I want to change the data in controller.js into the data in the file requested by $http.get("grade.json").success(function(data).

The data of grade.json is as follows:

An error will occur. . .

Why? .

仅有的幸福
仅有的幸福

reply all(4)
左手右手慢动作

Since instructions are used, try to use independent scopes to maintain the independence of instructions. In your situation, you can change it to this

.directive('linearChart', function () {
    return {
        scope: {
            chartData: '=chartData'
        },
        restrict: 'EA',
        template: '<svg width="400" height="200"></svg>',
        link: function (scope, element, attrs) {
            scope.$watch('chartData', function (newData, oldData) {
                if (!newData) return;
                drawLineChart(newData);
            });

            function drawLineChart(data) {
                //todo
            }
        }
    }
})
迷茫

It’s done. . . You can print the corresponding value of your salesDataToPlot,看看是不是null,报错提示应该就是那里的原因;还有指令与控制器之间的数据传递要么使用独立作用域,然后使用scope parameter binding in the instruction; or use the inherited scope.

过去多啦不再A梦

The key in the json file must be in double quotes

滿天的星座

This is asynchronous during the $http request, and the directive is already being compiled when the dom is loaded. At that time, salesData is of course undefined.

You should be like this

$http.get(api)
    .then(function(res) {
        appendChart();  //这时才把指令加载到dom里去
    })

= = OMG, can the questioner ask the question without directly posting the screenshot of the code? segmentfault supports markdown syntax, dear

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template