AngularJS创建新的$ scope,减去从JSON数组中消耗的两个$ scope

时间:2015-08-09 03:03:03

标签: arrays json angularjs scope

我对AngularJS和编程非常陌生,我确信这是一个基本问题,但我很难找到我们的资源,如何实现从JSON文件中减去两个$ scope值($ scope.carrierDiff) )。我很感激您提供的任何帮助。

<!doctype html>
<html ng-app="MyApp">
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="Scripts/angular.min.js"></script>
</head>
<body >
    <div ng-controller="SiteCtrl">
        <ul ng-repeat="site in sites">
            <li>{{site.ID}}</li>
            <li>{{carrierDiff}}</li>
       </ul>
    </div></body>
<script>
    var app = angular.module("MyApp", []);
        app.controller("SiteCtrl", function($scope, $http) {
            $http.get('JSON/getsamplesitesCopy.json').
            success(function(data, status, headers, config) {   
                $scope.sites = data;
            $scope.carrierDiff = $scope.sites.Carrier - $scope.sites.Carrier2;
}).
error(function(data, status, headers, config) {
// log error
});
});
</script>
</html>

2 个答案:

答案 0 :(得分:0)

由于我对您正在检索的文件中返回的内容知之甚少,所以您似乎错误地引用了JSON数据。您需要引用$ scope.sites OR数据,而不是两者的黑客攻击版本。如果数据结构如下所示:

data = {Carrier: 5, Carrier: 4}

然后你会像这样引用Carrier:

data.Carrier1

因此,当您将数据移动到$ scope.sites时,您将引用数据中的JSON,并且无需指出它来自数据

$scope.sites.Carrier1

所以你的代码看起来应该是这样的: http://plnkr.co/edit/nnfewy?p=preview

<!doctype html>
<html ng-app="MyApp">
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="Scripts/angular.min.js"></script>
</head>
<body >
    <div ng-controller="SiteCtrl">
        <ul ng-repeat="site in sites">
            <li>{{site.ID}}</li>
            <li>{{carrierDiff}}</li>
       </ul>
    </div>
<script>
    var app = angular.module("MyApp", []);
        app.controller("SiteCtrl", function($scope, $http) {
            $http.get('JSON/getsamplesitesCopy.json').
            success(function(data, status, headers, config) {   
                $scope.sites = data;
            $scope.carrierDiff = $scope.sites.Carrier - $scope.sites.Carrier2;
}).
error(function(data, status, headers, config) {
// log error
});
});
</script>
</body>
</html>

要记住的另一个项目,你应该在头部或身体中有<script>,而不是在外面。请参阅上面代码中的修改。

答案 1 :(得分:0)

无需单独计算

$ scope.carrierDiff = $ scope.sites.Carrier - $ scope.sites.Carrier2;

你必须这样做......

&#13;
&#13;
<body >
    <div ng-controller="SiteCtrl">
        <ul ng-repeat="site in sites">
            <li>{{site.ID}}</li>
            <li>{{site.Carrier - site.Carrier2}}</li>
       </ul>
    </div>
</body>
&#13;
&#13;
&#13;