gpt4 book ai didi

angularjs - 创建 $ionicModal 时使用 ‘this’ 作为范围

转载 作者:行者123 更新时间:2023-12-02 22:00:11 25 4
gpt4 key购买 nike

我在创建 $ionicModal 时似乎遇到问题当尝试将我的范围指定为 this 时而不是$scope .

由于我通过实例名称绑定(bind) Controller 中的所有内容,因此我没有使用 $scope Controller 内部。

因此,我按照Ionic Framework doc中的指示启动模式。并切换$scopethis

$ionicModal.fromTemplateUrl('my-modal.html', {
scope: this,
animation: 'slide-in-up'
}).then(function(modal) {
this.modal = modal;
});

当应用程序运行时,我收到以下错误:

undefined is not a function

它引用了ionic.bundle.js中的以下代码:

var createModal = function(templateString, options) {
// Create a new scope for the modal
var scope = options.scope && options.scope.$new() || $rootScope.$new(true);

我什至尝试分配另一个变量来表示 this并以这种方式运行它,但同样的错误仍然存​​在!

如果我不使用$scope在我的 Controller 中,在保持 this 的使用的同时加载模式的最佳方法是什么? ?这是不可能的还是我错过了什么?

编辑-根据要求,在原始内容中添加更多信息,

模板:

<div id="wrapper" ng-controller="MainCtrl as ctrl">
<button ng-click="ctrl.demo()">Demo Button</button>
</div>

Controller :

angular.module('MyDemo', ['ionic'])
.controller('MainCtrl', function ($ionicModal) {
var _this = this;
this.demo = function () {
//do demo related stuff here
}

$ionicModal.fromTemplateUrl('my-modal.html', {
scope: _this,
animation: 'slide-in-up'
}).then(function(modal) {
_this.modal = modal;
});
});

所以,基本上,我使用的是这里找到的第一种声明样式: https://docs.angularjs.org/api/ng/directive/ngController

编辑:已更改this_this $ionicModal里面

根据要求,这是一个包含上述代码的 plunker: http://plnkr.co/edit/4GbulCDgoj4iZtmAg6v3?p=info

最佳答案

由于 AngularJs 目前在使用“controller as”语法时设置 Controller 的方式,您只能拥有您自己在 Controller 函数中定义的任何函数和属性。为了访问$new() AngularJs 提供的用于创建子作用域的函数,您需要提供一个 AngularJs $scope 对象——您仍然可以通过将其注入(inject)到构造函数中来获得该对象,即使使用“controller as”语法也是如此.

angular.module('MyDemo', ['ionic'])
.controller('MainCtrl', function ($scope, $ionicModal) {
var _this = this;
this.demo = function () {
//do demo related stuff here
}

$ionicModal.fromTemplateUrl('my-modal.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function(modal) {
_this.modal = modal;
});
});

关于angularjs - 创建 $ionicModal 时使用 ‘this’ 作为范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25854422/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com