【发布时间】:2016-06-08 16:07:28
【问题描述】:
我已经使用 angular-ui 和 angularjs 有一段时间了,遇到了一个问题,随后找到了解决方案,但我想知道这是否是一个好方法。最初的问题是处理将指令范围内的对象传递给模式。我在 SO 上找到的大多数建议都涉及解决:
resolve:将被解析并传递给控制器的成员 当地人: AngularJS - Pass object data into modal
我对这些建议的问题是,如果您需要将不同的对象从范围传递到不同模式的模式,则每个模式需要两个控制器。一个用于 open() 方法/$modal 服务,另一个用于实际的 $modalinstance。这是因为需要针对不同的模态以不同的方式解析不同的对象。我决定不使用多个解析,为什么不使用一个可以在 html 中定义的对象来保存您希望传递给模态的指令范围内的所有其他对象?
代码如下 - 在 test.html 指令模板之前,一切都应该看起来很普通。
app.js:
var app = angular.module('modalscope', ['ui.bootstrap']);
app.controller('ModalCtrl', function($scope, $modal){
$scope.open = function(modal_scope){
var modalInstance = $modal.open({
scope: $scope,
templateUrl: 'modal-content.html',
controller: 'ModalInstanceCtrl',
resolve: {
modal_scope: function() {
$scope.modal_scope = modal_scope;
return $scope.modal_scope;
}
}
});
};
});
app.controller('ModalInstanceCtrl', function($scope, $modalInstance, modal_scope){
$scope.names = modal_scope.names;
$scope.selName = modal_scope.selName;
$scope.ok = function(){
$modalInstance.close({ });
};
});
app.directive("appList", function() {
return {
restrict: 'E',
templateUrl: "test.html",
'link': function(scope, iElement, iAttrs) {
scope.names = [ {"name":"john"},{"name":"joe"},{"name":"mary"}];
}
};
});
index.hmtl:
<html ng-app="modalscope">
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.11.0/ui-bootstrap-tpls.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<app-list></app-list>
</body>
</html>
test.html:
<div ng-controller="ModalCtrl">
<h2 ng-repeat="name in names">{{name.name}}<button ng-click="open({'names':names,'selName':name });">Click</button></h2>
</div>
modal_content.html:
<h2>modal test</h2>
<p>name: {{selName.name}}</p>
<button class="btn btn-success" ng-click="ok()">OK</button>
基本上,我当前的实现会导致问题吗? 有没有更好的方法来避免为每个模态编写多个控制器/解析一长串潜在的范围对象,而不是像我那样为模态实例的范围解析单个容器对象:
"open({'names':names,'selName':name });"
【问题讨论】:
-
resolve 不会传递作用域,它作为依赖传递给目标控制器。为了设置范围,您可以使用您已经在做的设置的
scope属性。您可以使用var modalScope = $scope.$new(); modalScope.prop = "val"; //etc创建一个新范围并在设置中设置scope: modalScope,。 -
我尝试只使用范围:$scope,但在没有解析语句的情况下无法在模态实例中访问这些值。是否需要从解析传递依赖项?或者是否有不同的方式将范围从指令传递到模态?
-
我遇到的另一个问题是尝试从模态访问 ng-repeat 中的“名称”。这就是我将 selName 传递给 modal_scope 对象中的模态控制器的原因。有没有更好的办法?
标签: angularjs angularjs-scope angular-ui-bootstrap bootstrap-modal