控制器之间共享模型

编程入门 行业动态 更新时间:2024-10-10 21:21:47
本文介绍了控制器之间共享模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在攀登angular.js我的学习曲线,并试图了解在哪里把一切。

I'm climbing my learning curve in angular.js and try to understand where to put everything.

在这种情况下,我想知道,如果它是使用服务共享控制器之间的模式的最佳实践。

In this case I want to know if it is a best practice to use services to share the model between controllers.

var app = angular.module('module', []) .factory('shared', ['$http', function ($http) { var factory = { "title" : "Shared Title 2" }; factory.action = function () { // do something with this.title; } return factory; }]) .controller('MainCtrl', ['$scope','shared', function($scope, shared) { $scope.shared = shared; }]) .controller('SecondaryCtrl', ['$scope','shared', function($scope, shared) { $scope.shared = shared; }]);

小例子:

思维的角度:这是很好的做法,分享这样​​的模式

'thinking in angular': It is good practice to share the model like this?

推荐答案

我强烈建议您使用的是这样的服务良方。此外,不要简单地做一个公开的模型作为服务的服务。即不要做到这一点:

I strongly recommend using the Service recipe for something like this. In addition, do not simply make a service that exposes the model as the service. i.e. dont do this:

.service('UserService', function(){ return { changePassword: ... updateUsername: ... addEmail: ... }; });

相反,让服务成为与模型交互的接口:

Instead, let the service be an interface for interacting with the model:

.service('UserService', function(User){ return { getById: ... getAll: ... save: ... }; });

和做一个模型值是你的对象重新presentation:

And make a model value to be your object representation:

module.value('User', function(){ //user business logic });

更多推荐

控制器之间共享模型

本文发布于:2023-08-03 14:28:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1287674.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:控制器   模型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!