单击链接时,将AngularJS$作用域变量传递给新控制器

Pass an AngularJS $scope variable to new controller when link clicked

本文关键字:变量 控制器 作用域 链接 AngularJS 单击      更新时间:2023-09-26

我有一个应用程序,它使用动态路由加载模式窗口,每个窗口显示一个JSON文件中的"活动"对象。目前,我正在使用路由来确定哪张卡是可见的,然后调用数据服务来根据与路由名称的匹配来填充数据。

但我不喜欢这个解决方案,因为它将我当前的卡与数组的上下文隔离开来。我更希望能够从模板中传递card对象,因为这样我就会知道$index是什么,然后我可以使用它来导航到"prev"answers"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('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(解析成员的定义,该成员将被解析并作为本地人传递给控制器;它相当于AngularJS路由的resolve属性)将作用域对象传递给模式窗口控制器。所以在你的情况下,它可以这样做:

.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();
};
}])

在模态控制器中:

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();
    };
}