我不是 AngularJS 专家,我有一个简单的问题。
我的代码在页面开头定义了一个应用程序和 Controller :
<script>
var isisApp = angular.module('isisApp', []);
isisApp.controller('AccountListCtrl', function($scope) {
$scope.sample = {'firstName': 'John', 'lastName': 'Smith', 'age': 25, 'AccountType': 'Safekeeping',
'address': {'street': 'Dorsstok', 'city': 'Erica'},
'phone': [{'type': 'home', 'number': '+31591302900'}, {'type': 'mobile', 'number': '+31625299740'}, {'type': 'Business', 'number': '+43223627551'}],
'account': [{'type': 'Bonds', 'value': '111111'}, {'type': 'Stocks', 'value': '$ 0625299740'}, {'type': 'Funds', 'value': '999990'}],
'json_read_date': '4/12'
};
});
</script>
例如,我会在构建图表 (ChartJS) 的外部环境中使用 json_read_date,如何读取那里的变量?我有一个像这样的样本,但它不起作用:
var read_date= $('[ng-controller="AccountListCtrl"]').scope().json_read_date;
我得到这个错误:'undefined' 不是一个函数等。
你有什么想法吗?我在 body 标签内使用 ng-controller="AccountListCtrl",我的第二个脚本也是..
提前致谢! 法比奥
在 Isha 的回答后我修改了我的代码,但是我看不到任何图表:
<!-- Graph !-->
<canvas id="canvas" height="450" width="450"></canvas>
<script>
isisApp.controller('ChartJS', function($scope, Init) {
$scope.init = Init;
var delivery = $scope.init.json_doughnut_delivery;
var taxother = $scope.init.json_doughnut_taxother;
var supply = $scope.init.json_doughnut_supply;
var doughnutData = [
{
value: delivery,
color: "#000000"
},
{
value: taxother,
color: "#838383"
},
{
value: supply,
color: "#FFFF00"
}
];
var myDoughnut = new Chart(document.getElementById("canvas").getContext("2d")).Doughnut(doughnutData);
});
</script>
在它简单地工作之前:
<!-- Graph !-->
<canvas id="canvas" height="450" width="450"></canvas>
<script>
var doughnutData = [
{
value: 32,
color: "#000000"
},
{
value: 23,
color: "#838383"
},
{
value: 11,
color: "#FFFF00"
}
];
var myDoughnut = new Chart(document.getElementById("canvas").getContext("2d")).Doughnut(doughnutData);
</script>
最佳答案
您可以使用factory
提供sample
数据并将其注入(inject)其他 Controller 、指令...
isisApp.factory('Sample', function(){
return {'firstName': 'John', 'lastName': 'Smith', 'age': 25, 'AccountType': 'Safekeeping',
'address': {'street': 'Dorsstok', 'city': 'Erica'},
'phone': [{'type': 'home', 'number': '+31591302900'}, {'type': 'mobile', 'number': '+31625299740'}, {'type': 'Business', 'number': '+43223627551'}],
'account': [{'type': 'Bonds', 'value': '111111'}, {'type': 'Stocks', 'value': '$ 0625299740'}, {'type': 'Funds', 'value': '999990'}],
'json_read_date': '4/12'
};
});
isisApp.controller('AccountListCtrl', function($scope, Sample){
$scope.sample = Sample;
//now you have an access 'json_read_date' inside this controller, via - Sample.json_read_date OR $scope.sample.json_read_date
});
isisApp.controller('ChartJS', function($scope, Sample){
$scope.sample = Sample;
//now you have an access 'json_read_date' inside this controller, via - Sample.json_read_date OR $scope.sample.json_read_date
});
希望对你有帮助。
关于javascript - AngularJS,如何在 HTML 的外部 JS <script> 中使用变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22012002/