javascript - Angular 1 - 在父 Controller 和子 Controller 之间共享数据 - 需要建议

标签 javascript angularjs

我正在开发 2 个应用程序,这些应用程序将仅显示所有事件事件,然后显示所有已关闭事件。这两个应用程序在创建、修改、保存和删除方面具有相似的逻辑。

所以我试图找出在两个应用程序之间共享 CRUD 逻辑的最佳方法。我认为也许最好像这样设置父子 Controller 设置:

Common_CRUD_file.js:

var Common_Application = .module('Common_Application ',[app, app1, app2, app3])
Parent_controller.controller('Parent_controller'), function ($scope, $http, $filter, $timeout) {

//all my CRUD logic goes in here
$scope.edit = function(data) { //edit logic goes here }
$scope.save = function(data) { //save logic goes here }
$scope.cancel = function(data) { //cancel logic goes here }
$scope.delete = function(data) { //delete logic goes here }

}

Child_Show_close_incidents.js:

var Common_Application = angular.module('Common_Application');
Child_controller.controller('Child_controller'), function ($scope, $http, $filter, $timeout) {

//All of the app logic goes here    
$scope.get_data = function(data) { //store fetched ajax data in $scope.All_closed_incidents  }

}

HTML 文件的快速摘录:

<div ng-app="Common_Application" ng-controller="Parent_controller">
<div ng-controller="Child_controller">
<table directive_for_angular_app_here>
  <tr>
    <td></td>
    <td>Description</td>
    <td>Status</td>
  </tr>
  <tr ng-repeat="incident in All_closed_incidents">
    <td><button type="button" ng-click="edit(incident)">Edit</button></td>
    <td>{{incident.Description}}</td>
    <td>{{incident.Status}}</td>
  </tr>  
</div>
</div>

因此,此设置能够加载我的表格,但当我单击按钮时,编辑功能似乎根本不触发。控制台也没有错误。当我期望它共享其所有范围时,似乎完全忽略了我的父函数。有人对此有更好的解决办法吗?

最佳答案

我会放弃你拥有的父/子设置。将父级变成具有以下功能的服务:

    //all my CRUD logic goes in here
$scope.edit = function(data) { //edit logic goes here }
$scope.save = function(data) { //save logic goes here }
$scope.cancel = function(data) { //cancel logic goes here }
$scope.delete = function(data) { //delete logic goes here }

然后将该服务注入(inject)子 Controller 并调用函数。降低复杂性并增强可重用性。

关于javascript - Angular 1 - 在父 Controller 和子 Controller 之间共享数据 - 需要建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41126262/

相关文章:

javascript - 如何通过点击事件与 Node.js 服务器通信?

javascript - 使用动态生成的数据数组进行 ng-repeat 的性能

javascript - 是否可以定义一个解析对象并使其在所有路由中可用?

javascript - 如何在 Angular JS 中使用带有 Http 请求的服务

Javascript 全局变量

JavaScript 对象 : a function or method in an attribute

javascript - 如果数据存在于缓存中,AngularJS 会绕过 promise

javascript - 在路由内响应上下文

AngularJS - 如何公开服务属性

javascript - 通过使用 angularjs 拖动来动态更改模板