gpt4 book ai didi

javascript - 仅当未定义 AngularJS 时才通过

转载 作者:行者123 更新时间:2023-12-02 15:18:36 24 4
gpt4 key购买 nike

在我的代码中,我将 JSON 对象数组从我的服务传递到我的 Controller ,然后传递到我的指令以进行可视化。

Controller 中的代码:

(function(){

'use strict';

angular.module('dashboardApp').controller('DownloadCtrl', DownloadCtrl);

DownloadCtrl.$inject= ['DownloadService','$scope'];

function DownloadCtrl(DownloadService, $scope){
var self=this;

DownloadService.getRoutes()
.then(function(responseData){
self.routes = responseData.data;

});

}

})();

HTML 代码:

<div class="container" ng-controller="DownloadCtrl">    

<donut-chart data='download.routes'></donut-chart>

</div>

指令代码:

angular.module('dashboardApp').directive('donutChart',function(){

function link(scope,element,attr){
var dataSet = scope.data;

if(dataSet!==undefined){
var chart = c3.generate({
data: dataSet,
type:'donut'
});
}
};

return {
restrict: 'EA',
link : link,
scope: {
data: '='

}
};
});

如果我scope.$watch $scope.data,我注意到它出现一次并且没有分配数据,然后它再次出现并分配了数据。如果我没有 dataSet!==undefiend 那么代码将会失败。

它适用于当前的设置,但我觉得有一个比简单检查是否dataSet!==undefined更好的方法。我想我可能以不正确的顺序或不正确的方式做事。

我想要一种允许我删除 dataSet!==undefiend

最佳答案

如果 scope.datanull,您应该从链接函数返回

function link(scope,element,attr){
if(scope.data == null){
return;
}

var dataSet = scope.data;

var chart = c3.generate({
data: dataSet,
type:'donut'
});

};

关于javascript - 仅当未定义 AngularJS 时才通过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34266921/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com