我想为模态定义一个自定义范围(我不想使用依赖注入的原因)我在我的项目中使用,但是每当我在$modal.open
中定义一个范围时,我就会得到一个错误。下面是我从AngularUI的网站上创建的示例:http://plnkr.co/edit/rbtbpyqG7L39q1qYdHns
我尝试调试并看到(modalOptions.scope || $rootScope)
返回true
具有自定义作用域,并且由于true
(显然)没有定义$new()
函数,因此抛出异常。
任何想法吗?
你必须传递一个作用域实例:
var modalInstance = $modal.open({
animation: $scope.animationsEnabled,
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
size: size,
resolve: {
items: function () {
return $scope.items;
}
},
scope: $scope
});
如果你不想使用控制器的作用域,你也可以传入你自己的自定义作用域,工作plnkr:
http://plnkr.co/edit/1GJTuVn45FgPC3jIgyHv?p =预览
First Way
传递一个变量到一个模态,你可以这样做
var modalInstance = $modal.open({
animation: $scope.animationsEnabled,
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
size: size,
resolve: {
items: function () {
return $scope.items;
},
test: function(){
return $scope.test; //This is the way
}
}
});
在你的模态中有这个
angular.module('ui.bootstrap.demo').controller('ModalInstanceCtrl', function ($scope, $modalInstance, items, test) {
$scope.items = items;
$scope.test = test; // And here you have your variable in your modal
console.log("Test: " + $scope.test)
$scope.selected = {
item: $scope.items[0]
};
$scope.ok = function () {
$modalInstance.close($scope.selected.item);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
这里你有你自己的例子在Plunker
第二种方式
var modalInstance = $modal.open({
animation: $scope.animationsEnabled,
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
size: size,
scope: $scope, // In this way
resolve: {
items: function () {
return $scope.items;
}
}
});
angular.module('ui.bootstrap.demo').controller('ModalInstanceCtrl', function ($scope, $modalInstance, items) {
$scope.items = items;
//You have available test and hello in modal
console.log("Test 1: " + $scope.test);
console.log("Test 2: " + $scope.hello);
$scope.selected = {
item: $scope.items[0]
};
$scope.ok = function () {
$modalInstance.close($scope.selected.item);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
第二路活塞