使用angularjs中的模态

时间:2015-07-21 09:49:21

标签: javascript angularjs ng-repeat bootstrap-modal

我这里有这段代码

<div ng-repeat="item in items" class="col-sm-4 portfolio-item">
         <script type="text/ng-template" id="myModalContent.html">

但是,我无法在脚本代码中访问{{item}}。有没有办法可以从div标签之外插入id和type?对不起新手问题。

以下是控制器的代码:

.controller('listCtrl', function($scope, $modal, $log, $stateParams, items) {

    $scope.animationsEnabled = true;

    $scope.open = function(size) {

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

        modalInstance.result.then(function(selectedItem) {
            $scope.selected = selectedItem;
        }, function() {
            $log.info('Modal dismissed at: ' + new Date());
        });
    };

    $scope.toggleAnimation = function() {
        $scope.animationsEnabled = !$scope.animationsEnabled;
    };

})

// Please note that $modalInstance represents a modal window (instance) dependency.
// It is not the same as the $modal service used above.

.controller('ModalInstanceCtrl', function($scope, $modalInstance, items) {

    $scope.items = items;
    $scope.selected = {
        items: $scope.items
    };

    $scope.ok = function() {
        $modalInstance.close($scope.selected.item);
    };

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

1 个答案:

答案 0 :(得分:0)

您无法访问模态模板中的item对象,因为它是在$rootScope的隔离范围子项中编译的,因此模态内容无法继承项目。

您要做的是为模态实例提供基本范围。试试这个:

var modalInstance = $modal.open({
    scope: $scope, // <--- use this scope as the base for new scope
    animation: $scope.animationsEnabled,
    templateUrl: 'myModalContent.html',
    controller: 'ModalInstanceCtrl',
    size: size,
    resolve: {
        item: function() {
            return $scope.item;
        }
    }
});

在上面的代码片段中,模态服务将从传递的$ scope创建新的子范围,在这种情况下,模态范围将继承原型项目对象。