简体   繁体   English

在AngularJS中遍历或查询$ scope

[英]Traversing or querying $scope in AngularJS

I have a nested structure with directives and controllers, and from the leaf of this structure I have to access a scope property of the root controller. 我有一个带有指令和控制器的嵌套结构,从该结构的叶中,我必须访问根控制器的scope属性。 I'm doing it in this way: 我这样做是这样的:

$scope.$parent.$parent.$parent.property.value.push({ name: "Diego" });

but it's ugly and unreliable. 但这是丑陋且不可靠的。 I wonder if there's a better way to do it, maybe querying the scope? 我想知道是否有更好的方法,也许查询范围? I noticed that every $scope has an ID, may it be used to retrieve the scope without traversing the whole structure? 我注意到每个$ scope都有一个ID,是否可以将其用于检索范围而不遍历整个结构? Thanks. 谢谢。

I would do this with the help of $broadcast and $on. 我将在$ broadcast和$ on的帮助下完成此操作。 See the Scope docs 请参阅范围文档

In the directive you would do something like: 在指令中,您将执行以下操作:

$rootScope.$broadcast('directiveName.message', {name: 'Diego'});

And in the controller you would listen for the events like this: 在控制器中,您将侦听此类事件:

$rootScope.$on('directiveName.message', function(message) {
    console.log(message.name);
});

AngularJS is built around the idea of dependency injection. AngularJS是围绕依赖注入的思想构建的。 As such, querying for data outside of your scope is discouraged. 因此,不建议查询您范围之外的数据。

You have several options: 您有几种选择:

  • If you need to access the $rootScope , you can simply ask AngularJS to inject it. 如果您需要访问$rootScope ,则只需让AngularJS注入它即可。

For example, if you use a controller: 例如,如果您使用控制器:

myApp.controller('myCtrl', function ($rootScope) {
  // AngularJS will recognize the parameter and populate it
  $rootScope.property.value.push({name: 'Diego'});
});

For example, you could attach a directive controller to the body and share it with any directive in children: 例如,您可以将指令控制器附加到主体,并与子代中的任何指令共享它:

myApp.directive('body', function () {
  return {
    restrict: 'E',

    controller: function () {
      this.hello = function () { … };
    }
  };
});

myApp.directive('myDir', function () {
  return {
    require: '^body',

    link: function (scope, element, attr, bodyCtrl) {
      bodyCtrl.hello();
    }
  };
});
  • Finally, you can also make a singleton service and require it whevener you need it. 最后,您还可以进行单例服务,并在需要时进行请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM