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

标签 angularjs modal-dialog angularjs-scope ionic-framework

我在创建 $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/

相关文章:

AngularJS:从 HTML 中的数据初始化模型?

javascript - 在 Angular 单元测试中应该如何处理运行 block ?

jquery - AngularJS $http 和 jQuery AJAX 仅在移动浏览器上不触发

javascript - 获取已执行规范文件的文件名

javascript - 如何在 Angular 中使用相同的 ng-model 从多个输入字段中检索文本

javascript - 关闭对话框时留下灰色阴影

javascript - 为什么 JS 模态消息框在 setTimeout() 上暂停倒计时?

javascript - 单个 ESC 关闭 jQuery UI 中的所有模式对话框。解决方法?

angularjs - Angular 将服务属性绑定(bind)到 Controller 范围

javascript - Angular : Access scope from within &lt;script&gt; tag