如何将函数变量传递给Bootstrap UI模式?

时间:2015-04-21 08:58:13

标签: angularjs angular-ui-bootstrap bootstrap-modal

点击打开按钮时,我需要将变量传递给我的模态。我想用角度bootstrap ui模态来做。我需要这个,因为我将为每个页面使用可重用的模态,并根据页面我想要更改模态的内容。

我将变量命名为' x'例如。

以下是我正在处理的代码:

在第二个警告中,对象为空,如果有人有解决方案,即使使用其他模式编码风格,我将不胜感激:)

脚本:

angular.module('plunker', ['ui.bootstrap']);
var ModalDemoCtrl = function ($scope, $modal, $log) {

     $scope.open = function (x) {
         var modalInstance = $modal.open({
             templateUrl: 'myModalContent.html',
             controller: ModalInstanceCtrl,
             resolve: {
                 x: function () {
                     return $scope.x;
                 }
             }
         });
         alert(x);
     };
};

var ModalInstanceCtrl = function ($scope, $modalInstance, x) {
    alert(x);
    $scope.ok = function () {
        $modalInstance.close();
    };

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

HTML:

<!doctype html>
<html ng-app="plunker">
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.js"></script>
    <script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.6.0.js"></script>
    <script src="example.js"></script>
    <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
</head>
<body>

    <div ng-controller="ModalDemoCtrl">
        <script type="text/ng-template" id="myModalContent.html">
        <div class="modal-header">
            <h3>Title</h3>
        </div>
        <div class="modal-body">
            {{ x }}
        </div>
        <div class="modal-footer">
            <button class="btn btn-primary" ng-click="ok()">OK</button>
            <button class="btn btn-warning" ng-click="cancel()">Cancel</button>
        </div>
        </script>

        <button class="btn" ng-click="open('x')">Open</button>
    </div>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

您从未存储变量&#39; x&#39;在$ scope中。 我修复了您的示例 - 请参阅plunker

angular.module('plunker', ['ui.bootstrap']);
var ModalDemoCtrl = function ($scope, $modal, $log) {

   $scope.open = function (x) {
     var modalInstance = $modal.open({
         templateUrl: 'myModalContent.html',
         controller: ModalInstanceCtrl,
         resolve: {
             x: function () {
                 return x; // <-- just use the function parameter
             }
         }
     });
   };
};

var ModalInstanceCtrl = function ($scope, $modalInstance, x) {
    $scope.x = x; // store x in the scope
    $scope.ok = function () {
        $modalInstance.close();
    };

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