我有一个应用程序,它使用动态路由来加载模态窗口,每个窗口都显示 JSON 文件中的一个“事件”对象。目前,我正在使用路线来确定哪张卡可见,然后调用数据服务来根据与路线名称的匹配来填充数据。
但我不喜欢这个解决方案,因为它将我当前的卡与数组的上下文隔离。我更希望能够从模板传递卡片对象,因为这样我就会知道 $index 是什么,然后我可以使用它导航到“prev”和“next”元素。
如果我有这个标记:
<div ng-controller="MenuCtrl">
<ul class="menu">
<li ng-repeat="card in cards">
<a href="#/page/{{ card.shortName }}">{{ card.shortName }} </a>
</li>
</ul>
</div>
这会触发这个$routeProvider:
$routeProvider
.when('/page/:name', {
templateUrl : 'modalContainer',
controller : 'ModalContainerCtrl'
})
这会调出这个 Controller :
.controller('ModalContainerCtrl',['$scope', '$modal', '$route', function($scope, $modal, $route) {
var modalInstance = $modal.open({
templateUrl : '../assets/templates/modal.html',
controller: 'ModalCtrl'
});
$scope.activity = $route.current.pathParams.name;
console.log($scope.activity);
//Modal controls
$scope.close = function () {
console.log("close!");
$modalInstance.close();
};
}])
有什么方法可以通过此路由或任何其他方式将 card
对象传递给 ModalContainerCtrl
吗?
最佳答案
您可以使用resolve(将被解析并作为局部变量传递到 Controller 的解析成员的定义;它相当于AngularJS路由的resolve属性)将范围对象传递到模式窗口 Controller 。因此,根据您的情况,可以这样做:
.controller('ModalContainerCtrl',['$scope', '$modal', '$route', function($scope, $modal, $route) {
//your card object
$scope.card = '';
var modalInstance = $modal.open({
templateUrl : '../assets/templates/modal.html',
controller: 'ModalCtrl',
resolve: {
card: function () {
return $scope.card;
}
}
});
$scope.activity = $route.current.pathParams.name;
console.log($scope.activity);
//Modal controls
$scope.close = function () {
console.log("close!");
$modalInstance.close();
};
}])
在模态 Controller 中:
var ModalCtrl = function ($scope, $modalInstance,card) {
//Modal controls
//card now can be used over here
$scope.close = function () {
console.log("close!") //This will now run
modalInstance.close();
};
}
关于javascript - 单击链接时将 AngularJS $scope 变量传递给新 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25952010/