javascript - 闭包中的多个 Controller AngularJS

标签 javascript angularjs

我在闭包内创建了 2 个 Controller :

_closure = (function(){

var _One; 
var _Two;


//register module- left out for brevity

function ctrlOne($scope){

this.model = {
a : 'a'
b:'b'
}

_One = $scope;

}

function ctrlTwo($scope){

this.model = {
c : 'c'
d:'d'
}

_Two = $scope;

}

//assign controllers to module- left out for brevity


var publicMethods = {

saveAll: function(){

// access both the models in this function. 

}


}


})()

我想访问我的公共(public)函数中的模型(因为我目前正在现有框架中改造 Angular )。我想知道为两个 Controller 的范围分配引用是否正确?在这里,我只是保留了一个指向 $scope 的指针(在 _One 和 _Two 中),然后尝试在 SaveAll 公共(public)方法中访问它们各自的模型。这是正确的做法吗?

最佳答案

这有几个问题,我同意 New Dev 的观点,你应该“尽早放弃这个想法”

1) 您在此 IIFE 中没有返回任何内容,因此 _closure 变量将变为 undefined

2) 在 Angular 中,$scope 对象是模型,并且新的 $scope 被传递到每个 Controller 函数中。所以你可以有这样的东西:

angular.module('myApp', [])
.controller('ctrlOne', function($scope){
  $scope.a = 'a';
  $scope.b = 'b';
})
.controller('ctrlTwo', function($scope){
  $scope.c = 'c';
  $scope.d = 'd';
});

3) 我不确定您当前如何将 Controller 连接到应用程序,因此也许 this.model 约定有效,但您通常不使用关键字 this 在 Controller 内。

4) 在 _One_Two 中保留指向 $scope 的指针并不是解决此问题的正确方法。您可以使用provider,而不是寻找一种方法来维护对该 Controller 功能之外的特定 Controller 范围的访问。 (服务或工厂)代替您的公共(public)方法。提供程序保存应用程序的所有业务逻辑,听起来这就是您的公共(public)函数正在执行的操作(即 saveAll)。

使用 Angular 改造某些东西可能会非常快 - 但前提是您知道自己在做什么。 Angular 确实令人困惑且难以掌握,除非您非常了解您的工具,否则您将很难使用它们。我建议从ng-newsletter's fantastic beginner tutorial开始

关于javascript - 闭包中的多个 Controller AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27613358/

相关文章:

javascript - 执行函数时更改 div 中的文本

javascript - Mustache - 以使用相同名称的嵌套部分为条件

javascript - ng-select 不适用于渲染数组列表?

javascript - 将复选框值传递给 Angular 的 ng-click

css - 如何根据里面的文字设置元素的宽度?

javascript - 如何使用javascript禁用浏览器中的最大化选项

javascript - 使用 Web Audio API 或任何 Javascript 音频库(如 howler.js、tone.js)的音频效果(左右声道之间有 20 毫秒的延迟)?

javascript - [attribute != "value"] 是否存在于 CSS 中的任何位置,还是我刚刚编造的?

javascript - 我如何在 CucumberJS 中跨多个步骤定义文件共享我的 World 实例?

javascript - 较小屏幕的下拉选择