javascript - 在 Angular.js 中连接模型

标签 javascript frameworks model angularjs

我刚刚开始使用 Angular.js,我不确定如何将两个“模型”“链接”在一起。我的 index.php 文件中有以下代码

<div ng-controller="AccountCtrl">
    <h2>Accounts</h2>
    <ul>
        <li ng-repeat="account in accounts">
            <span>{{account.id}} {{account.ownedBy}}</span>
        </li>
    </ul>
</div>
<div ng-controller="TransactionCtrl">
    <h2>Transactions</h2>
    <ul>
        <li ng-repeat="transaction in transactions">
            <span>{{transaction.id}} {{transaction.timestamp}} {{transaction.amount}} {{transaction.description}} {{transaction.account}}</span>
        </li>
    </ul>
</div>

以及下面的js

function AccountCtrl($scope, $http) {
    // initialize Data
    $http({
        method:'GET', 
        url:'http://api.mydomain.ca/accounts'
    }).success(function(data, status, headers, config) {
        $scope.accounts = data;
    }).error(function(data, status, headers, config) {
        alert('Error getting accounts. HTTP Response status code: '+status);
    });
}
function TransactionCtrl($scope, $http) {
    // initialize Data
    $http({
        method:'GET', 
        url:'http://api.mydomain.ca/transactions'
    }).success(function(data, status, headers, config) {
        $scope.transactions = data;
    }).error(function(data, status, headers, config) {
        alert('Error getting transactions. HTTP Response status code: '+status);
    });
}

因此,在我的示例中,每个帐户都会有很多交易,我想向我的帐户 Controller 添加一个函数,以根据交易计算帐户的余额,但我不确定如何执行此操作,因为它们处于不同的状态$范围。

有没有办法在 Angular 中执行此操作,或者当我获取帐户时,我是否必须从服务器的 JSON 响应中返回“链接”交易信息?

最佳答案

我猜帐户持有交易,对吧? 那么我想,您可以创建一个服务来管理帐户/交易数据。 将此服务注入(inject)到两个 Controller 中。

module = angular.module('app', []);

module.factory('accountService', function($http) {
  var obj = {
    // handles http communication to/from server.
    // also has methods/getters/setters for data manipulation, etc.
  };
  return obj;
});

module.controller('AccountCtrl', function($scope, accountService) {
   // access accountService for the view-databind.
});

module.controller('TransactionCtrl', function($scope, accountService) {
   // access accountService for the view-databind.
});

关于javascript - 在 Angular.js 中连接模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14489637/

相关文章:

django - 如何向 Django 中的模型添加临时字段?

ruby-on-rails - 从 Ruby on Rails 应用程序中的模型访问数据

javascript - 如何在选择下拉菜单中设计有序列表

javascript - Node : How to free buffers that get allocated outside of the V8 memory heap

javascript/jquery 计算当前行中选中的复选框的数量

java - 现有应用程序的 MVC 框架

javascript - 如何让NodeJS评估多个传统JS文件

.net - Entity Framework 和多线程

javascript - 用于数据网格(或电子表格)的 HTML5 javascript 框架

javascript - 使用模型存储在关卡中的数据中的某些字段不会被持久化