AngularJS Modal 中控制器之间的双向绑定

AngularJS Two way binding between controllers in Modal

本文关键字:绑定 之间 Modal 控制器 AngularJS      更新时间:2023-09-26

我的index.html包含一个可内容编辑的div和一个按钮。在按钮click(ng-click) ModalDemoCtrl控制器中的$uibModal.open()功能将打开一个模态窗口,然后调用控制器ModalInstanceCtrl,从而在模态中呈现各种笑脸。我希望当我单击模态窗口中的笑脸时,图像会在我index.htmlcontenteditablediv 中呈现

index.html

<div ng-controller="ModalDemoCtrl" id="angularData">
  <div id="view1">
      <button type="button" class="btn btn-default" ng-click="open('lg')">Emojis</button>
      <div contenteditable="true" ng-model="textModel"></div>
  </div>
</div>

emojis.js

angular.module('ui.bootstrap.demo')
.controller('ModalDemoCtrl', function ($scope, $uibModal, $log) {
  $scope.animationsEnabled = true;
  $scope.textModel = "Hello";
  $scope.open = function (size) {
    var modalInstance = $uibModal.open({
      animation: $scope.animationsEnabled,
      templateUrl: 'template/template.html',
      controller: 'ModalInstanceCtrl',
      windowClass: 'large-Modal',
    });
  };
});

angular.module('ui.bootstrap.demo')
.controller('ModalInstanceCtrl', function ($scope, $window, createEmojiIcon) {
  $scope.getUnicode = function(id) {  //This functions get the img tag of clicked smiley in variable 'input'
  var style = createEmojiIcon.createEmoji(icons[id]);
  var input = '<img src="img/blank.gif" class="img" style="' + style + '" alt="' + icons[id][3] + '" title="' + icons[id][3] + '">';
  }
});

我想要的只是这个称为输入的变量,以便在调用函数 $scope.getUnicode 时在 contenteditablediv 中呈现。

简单来说,当调用函数$scope.getUnicode时,ModalDemoCtrl中的 textModel 会附加 img 标记。

ps:函数$scope.getUnicodeng-clicktemplate.html中调用

这是普伦克样本。

您需要对

点击事件进行 rootScope 广播,因为您有 2 个独立的范围。

修复了您的代码。通过$rootScope广播将 X 从模型弹出窗口传递到其他控制器。

在 ModalInstanceCtrl 中

$rootScope.$broadcast('selectedCode', {message: 'x'});

在ModalDemoCtrl

$rootScope.$on('selectedCode', function(event, args){
   alert(args.message);
});

https://plnkr.co/edit/YE3u8JEXJ4mABOPhUJyg

亲爱的

您必须使用工厂或服务。但我会用工厂参考向您展示:

angular.module('ui.bootstrap.demo')
    .factory('myFactory', function() {
        return {
            setInput : function(data){
                input = data;
            }
            getInput : function(){
                return input;
            }  
        }
    });
    .controller('ModalDemoCtrl', function ($scope, $uibModal, $log) {
        $scope.input= myFactory.getInput();
        **//you'll get value what you set in controller below**
    });
    .controller('ModalInstanceCtrl', function ($scope, $window, createEmojiIcon){
        myFactory.setInput(data);
        **//you are setting value here**
    });

谢谢和干杯