我有这个带变量的函数,我想在我的控制器中使用它。
我的代码看起来像这样
ctrl.openModal= myItem => {
let modal = $uibModal.open({
templateUrl: 'path/to/my/template.html',
controller: 'modalController'
});
};
问题是我不知道如何访问控制器中的myItem
module.controller('modalController', function ($scope) {
console.log(myItem);
});
尝试记录它说它未定义。
答案 0 :(得分:1)
使用resolve
。喜欢:
resolve: {
myItem : function() {
return myItem;
}
}
然后在控制器中:
module.controller('modalController', function ($scope, myItem) {
console.log(myItem);
$scope.myItem =myItem;// assign to scope variable to acces in your modal template
});
//示例模态模板:
<script type="text/ng-template" id="template.html">
<div class="modal-header">
<h3 class="modal-title">modal template</h3>
</div>
<div class="modal-body">
{{ myItem }}
</div>
</script>
答案 1 :(得分:0)
使用范围将数据传递给模态:
// Create the modal scope
var modalScope = $rootScope.$new();
modalScope.item = {'foo': 'bar'};
var modal = $uibModal.open({
templateUrl: '/partials/modal.html',
controller: modalController
scope: modalScope
});
/**
*
* @param $scope The modal instance scope
* @param $uibModalInstance the modal instance (injected)
*/
function modalController($scope, $uibModalInstance) {
console.log($scope.item);
}
答案 2 :(得分:0)
您可以简单地resolve
您的参数。像这样:
ctrl.openModal= myItem => {
let modal = $uibModal.open({
templateUrl: 'path/to/my/template.html',
controller: 'modalController'
resolve: {
myItem: () => myItem
}
});
};
现在,您可以在控制器中注入myItem
:
module.controller('modalController', function ($scope, myItem) {
console.log(myItem);
});