如何将变量从父作用域传递到AngularJS中的子作用域

时间:2015-10-07 19:17:52

标签: javascript angularjs angularjs-scope

我有一个部分页面,其代码类似于以下内容:

<div class="selector-result row">
    <div ng-if="resultCtrl.result">
        <div class="col-xs-12">
            <h4><strong>We Recommend:</strong></h4>
            <h2><strong>{{resultCtrl.result.Name}}</strong></h2>
        </div>
        <div class="row">
            <div class="col-md-4">

                <div ng-controller="selectorResultCarouselController">
                    <div>
                        <div style="height: 305px">
                        <carousel interval="myInterval" no-wrap="false">
                            <slide ng-repeat="slide in slides" active="slide.active" actual="slide">
                            <img ng-src="{{slide.image}}" style="margin:auto;">
                            </slide>
                        </carousel>
                        </div>
                    </div>
                </div>
...

我有一个模块,它有一个带有controllerAs resultCtrl的指令(selectorResult)。那里还有一个控制器,selectorResultController,它可以加载变量&#39;结果&#39;。

我想做的是以某种方式将{{resultCtrl.result.AllImages}}导入selectorResultCarouselController,以便我可以将它们添加到我的轮播中。我输了。我真的很难理解Angular,我想我理解这些部分是如何工作的,我只是不理解系统,如果这是有意义的。

我只是想在这里寻找一点点。我已经阅读,阅读和阅读,但我没有看到任何能够解决这个问题的事情。

4 个答案:

答案 0 :(得分:3)

为避免$scope混淆,请考虑使用AngularJS's controllerAs syntax。基本上,不是将值附加到$scope,而是将它们附加到控制器对象本身。所以:

angular.module('myApp', [])
  .controller('ctrlOne', [function() {
    var self = this;
    self.name = 'ctrlOne';
  }])
  .controller('ctrlTwo', [function() {
    var self = this;
    self.name = 'ctrlTwo';
  }]);

<div ng-app="myApp">
  <div ng-controller="ctrlOne as one">
    <div ng-controller="ctrlTwo as two">
      <p>{{one.name}}</p> <!-- 'ctrlOne' -->
      <p>{{two.name}}</p> <!-- 'ctrlTwo' -->
    </div>
  </div>
</div>

答案 1 :(得分:2)

子范围继承自父级。所以只需使用$ scope.result.AllImages。

答案 2 :(得分:2)

  

“子范围”(原型)从其父范围继承属性。

来自:https://docs.angularjs.org/guide/scope

在您的情况下,在您的子范围内,您的变量可用$scope.result.Allmages

答案 3 :(得分:2)

如果您的指令具有隔离范围,则必须通过指令定义对象(ddo)中的属性将其绑定。属性&amp;,@和=将允许您执行此操作。

scope { myAttribute: '@', myOtherAttribute: '&', myLastAttribute: '='}

在你的指令中你会使用类似的东西:

<my-directive my-attribute="someString" my-other-attribute="someCallbackOnControllerScope()" my-last-attribute="somePropertyOnControllerScopeYouWantToBindTwoWays">

请注意,如果您使用&#39; @&#39;,它将作为字符串传递,您必须针对父作用域解析它以将其转换为对象(在指令中&#39;后链接功能):

$parse(myAttribute)(scope.$parent)

否则你的ddo可以将scope属性设置为false,在这种情况下它将使用父作用域。

如果你在ddo中将scope属性设置为true,你仍然可以寻址父范围属性(通过引用它就好像你没有子范围/就好像它在同一范围内已经可用),尽管要小心如果你这样做(范围:true)并且有多个相同的指令......因为它们将共享相同的范围,从而相互覆盖。

请查看此页面以获取更多信息:AngularJS Documentation

我希望这很有用