基于数据库实体创建模型


Create a model based on a Database entity

我是AngularJS的新手,我想了解如何正确地将模型与控制器分开。到目前为止,我一直使用控制器内部的模型。例如:

angular.module("app").controller("customerController", ["Customer", "$scope", "$routeParams",
    function (Customer, $scope, $routeParams){
        $scope.customer = Customer.find({ID:$routeParams.ID});
}]);

该函数从数据库中检索客户并将该客户公开给视图。但我想走得更远:例如,我可能有必要封装的东西或创建一些有用的函数从数据库中包含的行数据抽象。比如:

customer.getName = function(){
    //return customer_name + customer_surname
};
customer.save = function(){
    //save the customer in the database after some modifies
};

我想为Customer创建一个模型,并在许多控制器中重用该模型。也许我可以为客户创建一个List,并使用从数据库或其他地方检索所有客户的方法。

总之,我想有一个模型,反映一个数据库实体(如上面的客户)的属性和方法进行交互。也许还有一个工厂,它创建了一个Customer或一个Customer列表。我如何在AngularJS中实现这样的任务?我想听听你对这个问题的建议。一个简单的例子将是非常有用的,或者一个理论答案,帮助我理解在Angular中处理这些问题的正确方法。谢谢,祝你工作顺利。

Angular JS允许你在模型发生变化或发生事件时自动更新视图。声招呼它!

它是通过使用$watches来实现的,$watches是一种全局作用域java脚本对象,并且在angular js web应用的整个生命周期中都保留在主内存中。

1。在将任何内容放入 $作用域之前,请考虑数据的大小,因为您附加到它的每个数据对象都对$watch执行+1操作。当你从数据库中读取时,你可能有100+行,>4列,相信我,它会吞噬客户端处理。请考虑数据集的大小,并阅读有关大型数据集的角相关性能问题

2。要为您的数据库实体建立模型,我建议使用纯javascript类,即不要将所有内容放在$scope上(它将避免联合国必要的手表!)http://www.phpied.com/3-ways-to-define-a-javascript-class/

3。您希望在用户更改值时触发事件。为了这个最好的,我建议,如果你使用ng-repeat来渲染你的数组中的数据,然后使用$index来获得行号,其中的变化是完成的,并通过在ng-click即,并使用actionIdentifier来区分在各种事件你想要

ng-click="someFunc($index,actionIdentifier)"

您需要创建一个工厂/服务来完成这项工作,请查看jsfiddle

html:

<div ng-app="users-app">
  <h2>Users</h2>
  <div ng-view ></div>
  <script type="text/ng-template" id="list.html">
      <p>Users: {{(user || {}).name || 'not created'}}</p>
      <button ng-click='getUser()'>Get</button>
      <button ng-click='saveUser(user)'>Save</button>
  </script>
</div>

js:

angular.module('users-app', ['ngRoute'])
.factory('Users', function() {
    function User (user) {
        angular.extend(this, user);
    }
    User.prototype.save = function () {
        alert("saved " + this.name);
    }
    return {
        get: function() {
            return new User({name:'newUser'});
        }
    }
})
.config(function($routeProvider) {
  $routeProvider
    .when('/', {controller:'ListCtrl',templateUrl:'list.html'});
})
.controller('ListCtrl', function($scope, Users) {
   $scope.getUser = function() {
        $scope.user = Users.get();
    }
    $scope.saveUser = function(u) {
        u.save();
    }
})

希望有帮助,罗恩