简体   繁体   English

Angularjs:如何从模态控制器和指令控制器访问主控制器

[英]Angularjs: How to access main controller from modal controller and directive controller

I am new to Angularjs and working on a pet project. 我是Angularjs的新手并从事宠物项目。 I have a main page which has functions in HomeController . 我有一个主页面,在HomeController中有功能。 Then I have a button in the main page which on click opens a modal and the modal has a separate controller called ModalController . 然后我在主页面上有一个按钮,点击打开一个模态,模态有一个名为ModalController的独立控制器。 There is also a directive which is present in the modal which has its own controller. 模态中还有一个指令,它有自己的控制器。 I have 3 other places where I need to use date picker so I created a date picker directive and using it in all 3 places. 我还有其他3个地方需要使用日期选择器,所以我创建了一个日期选择器指令并在所有3个地方使用它。

I am not able to do the below functionalities. 我无法完成以下功能。

  1. Click on edit I opened a dialog but I need to open it with the row data and when pressed save should update the row. 点击edit我打开了一个对话框,但我需要用行数据打开它,按下保存时应该更新行。 ( The trouble I am facing here is how to get the value of the date which is directive's controller. ) 我在这里遇到的麻烦是如何获得指令控制器的日期值。
  2. Open Modal and enter the details and click save I need to create a new record and add it to the records which is present in the main controller. 打开Modal并输入详细信息并单击save我需要创建一条新记录并将其添加到主控制器中的记录中。 ( How save the data from Modal controller to Home controller records. ) 如何将模态控制器中的数据保存到Home控制器记录中。

script.js 的script.js

angular.module('myApp', ['ngAnimate', 'ui.bootstrap']);
angular.module('myApp').controller('HomeController', function($scope, $uibModal) {

  $scope.records = [{'date': new Date(), 'place': 'Bangalore'}];

    $scope.openModal = function() {
      $uibModal.open({
        templateUrl: 'modaldialog.html',
        controller: 'ModalController'
      });
    };

    // How to get the directive date-picker value and pass it and save it.
    $scope.edit = function(record) {
      $uibModal.open({
        templateUrl: 'modaldialog.html',
        controller: 'ModalController'
      });
    };

    $scope.addwithinCtrl = function() {
      var record = {'date': new Date(), 'place': 'Hyderabad'};
      $scope.records.push(record);
    };

});

angular.module('myApp').controller('ModalController', function($scope, $uibModalInstance) {
  // save the input and dismiss the dialog
  $scope.save = function() {
    // how to save the entered data before closing the dialog?
    $uibModalInstance.dismiss('cancel');
  };

  $scope.cancel = function() {
    $uibModalInstance.dismiss('cancel');
  };
});


angular.module('myApp').directive('dateDirective', function() {
  return {
    restrict: 'A',
    templateUrl: 'date.html',
    controller: function($scope) {
      $scope.format = 'dd-MMM-yy';

      $scope.open = function() {
          $scope.status.opened = true;
      };

        $scope.status = {
            opened: false
        };
    }
  }
});

Plunker: PLUNKER Plunker: PLUNKER

There are multiple steps you need to make yet in order to complete your task. 您需要完成多个步骤才能完成任务。 I will give you a good start regarding passing data to and from modal controller and setting proper date to datepicker. 关于将数据传入和传出模态控制器并将正确的日期设置为datepicker,我将给你一个良好的开端。

First of all, make sure you isolate scope of the datepicker, it would make your life simpler in future. 首先,确保你隔离了datepicker的范围,这将使你的生活更加简单。 Then pass necessary model into this directive and bind it to datepicker (in datepicker template ng-model="model" ): 然后将必要的模型传递给该指令并将其绑定到datepicker(在datepicker模板ng-model="model" ):

angular.module('myApp').directive('dateDirective', function() {
    return {
        scope: {
            model: '=ngModel'
        },
        // ... rest of code is unchanged 
    }
});

Then you need to pass record object into modal controller. 然后你需要将记录对象传递给模态控制器。 For this you would use resolve instruction of the modal: 为此你将使用模态的解析指令:

$scope.edit = function(record) {
    $uibModal.open({
        resolve: {
            record: record
        },
        templateUrl: 'modaldialog.html',
        controller: 'ModalController'
    });
};

where in HTML you need to pass record to the edit function: 在HTML中你需要将record传递给edit功能:

<button class="btn btn-primary" type="button" ng-click="edit(record)">edit</button>

Finally, in order to update the original record you would need to subscribe to resolved promise returned by $uibModal.open method: 最后,为了更新原始记录,您需要订阅$uibModal.open方法返回的已解析承诺:

.controller('ModalController', function($scope, $uibModalInstance, record) {

    $scope.record = angular.copy(record);

    $uibModalInstance.result.then(function() {
        angular.extend(record, $scope.record);
    });

    // ...
});

Note, that in modal controller you need to make a copy of the original record and use it in modal template. 请注意,在模态控制器中,您需要复制原始记录并在模态模板中使用它。 This is necessary because you want to affect original record only if Save is pressed - then you extend original model with changed data. 这是必要的,因为只有在按下保存时才想影响原始记录 - 然后使用更改的数据扩展原始模型。

Demo: http://plnkr.co/edit/Hq0wFilQpZ26Ha2nyNxN?p=info 演示: http //plnkr.co/edit/Hq0wFilQpZ26Ha2nyNxN?p = info

Adding new record from outside of controller 从控制器外部添加新记录

As for your second question, this is another interesting question. 至于你的第二个问题,这是另一个有趣的问题。 Since in your original code you stored records in the scope array, this is actually not really convenient design solution for adding new records. 由于在原始代码中您将记录存储在作用域数组中,这实际上并不是用于添加新记录的非常方便的设计解决方案。 In real world you would likely have a separate model layer responsible for fetching existing and creating new records. 在现实世界中,您可能有一个单独的模型层负责获取现有和创建新记录。 In Angular you use services for this. 在Angular中,您可以使用服务 So you need to register a new service object with methods to get, update and save records. 因此,您需要使用方法注册新的服务对象以获取,更新和保存记录。 In terms of MVC it would correspond to M-layer. 就MVC而言,它将对应于M层。 Then whenever you want to add new record from any controller you would use this service which is singleton object same in every controller. 然后,无论何时您想要从任何控制器添加新记录,您都将使用此服务,该服务在每个控制器中都是相同的单一对象。

Here is an example of very simple service in your case: 以下是您的案例中非常简单的服务示例:

angular.module('myApp').service('records', function() {

    this.data = [{
        'date': new Date(),
        'place': 'Bangalore'
    }];

    this.fetch = function() {
        return this.data;
    };

    this.save = function(record) {
        this.data.push(record);
    };
});

And finally, here is complete example for your problem which can save new records both from controller and from outside using services and also allows editing. 最后,这里是您的问题的完整示例,它可以使用服务从控制器和外部保存新记录,还允许编辑。

Demo: http://plnkr.co/edit/NxP0HJurZuLA7odzzdie?p=preview 演示: http //plnkr.co/edit/NxP0HJurZuLA7odzzdie?p =preview

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

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