简体   繁体   English

如何在 Javascript 中使用工厂传递数组信息?

[英]How do I pass array information using a factory in Javascript?

Using a factory, I want to get information from one page (text fields and a submit button), put it in an array, and read from that array to post it into a different page.使用工厂,我想从一个页面(文本字段和提交按钮)获取信息,将其放入一个数组中,然后从该数组中读取以将其发布到不同的页面中。 Here is a snippet of my code.这是我的代码片段。

 app.factory("service", function(){ var serv = {}; serv.arr = []; serv.add = (title, name, post, tag) => serv.arr.push({ "title" : title, "name" : name, "post" : post, "tag" : tag }); return serv; }); app.controller("createCtrl", ["$scope", "service", function($scope, service) { display = () => service.add($scope.title, $scope.name, $scope.post, $scope.tag); console.log(service.arr); }]); app.controller("newsCtrl", ["$scope", "service", function($scope, service){ $scope.newsPage = "News"; $scope.array = service.arr; }]);

I know I'm probably way off but at this stage I can't even tell if any information is being added to the array.我知道我可能已经离开了,但在这个阶段我什至无法判断是否有任何信息被添加到数组中。

Try below code for set & get data from factory .尝试使用以下代码从factory setget数据。 Click on SAVE DATA & then GET DATA buttons to see the actions单击“ SAVE DATA ”,然后单击“ GET DATA按钮以查看操作

 (function(ng, app){ app = angular.module('app', []) app.factory("service", function(){ var serv = {}; var arr = []; return { add : function (title, name, post, tag) { arr.push({ "title" : title, "name" : name, "post" : post, "tag" : tag }); }, get : function (firstname) { return arr[0]; } } }); app.controller("createCtrl", ["$scope", "service", function($scope, service) { $scope.display = function(){ service.add($scope.title, $scope.name, $scope.post, $scope.tag); }; }]); app.controller("newsCtrl", ["$scope", "service", function($scope, service){ $scope.newsPage = "News"; $scope.getData = function(){ $scope.array = service.get(); }; }]); }(angular));
 input { margin: 5px; }
 <html ng-app="app"> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> </head> <body> <div ng-controller="createCtrl as main"> <h1>create Ctrl</h1> <input ng-model="title" placeholder="title" /><br/> <input ng-model="name" placeholder="name" /><br/> <input ng-model="post" placeholder="post" /><br/> <input ng-model="tag" placeholder="tag" /><br/> <button ng-click="display()"> SAVE DATA </button> </div> <br/> <hr/> <div ng-controller="newsCtrl"> <h2>news Ctrl </h2> <button ng-click="getData()"> GET DATA </button> <p> title : {{array.title}} </p> <p> name : {{array.name}} </p> <p> post : {{array.post}} </p> <p> tag : {{array.tag}} </p> </div> </body> </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM