AngularJS指令将函数执行顺序与require

时间:2016-04-21 11:59:36

标签: javascript angularjs

我已经看过这个video并且我有一个问题,我无法找到答案。有一个标题http://plnkr.co/edit/L8OMoB?p=preview

HTML

<div ng-app="app">
            <div ng-controller="MyCtrl">
                <my-select-view on="color">
                    <my-view label="Red" value="red"><span class="red-text">Red Content</span></my-view>
                    <my-view label="Blue" value="blue"><span class="blue-text">Blue Content</span></my-view>
                    <my-view label="Green" value="green"><span class="green-text">Green Content</span></my-view>
                    <my-view label="Something" value="something"><span class="something-text">Something Content</span></my-view>
                </my-select-view>
            </div>
        </div>

JS

angular.module('app', ['ngSanitize'])
        .directive("mySelectView", function($compile) {

            return {
                restrict: "E",
                scope: { item : "=on"},
                controller: function($scope, $element) {
                    $scope.views = [];

                    this.addView = function(label, value, content) {
                        $scope.views.push({ label: label, value: value, content: content });
                    }

                },
                link: function(scope, element, attrs, ctrl) {
                    var selectTpl = "<select ng-model='item'" +
                                    "        ng-options='view.value as view.label for view in views'" +
                                    "        ng-change='changeView()'></select>";

                    ...

                }
            }
        })
        .directive("myView", function() {
            return {
                restrict: "E",
                require: "^mySelectView",
                link: function(scope, element, attrs, ctrl) {
                    ctrl.addView(attrs.label, attrs.value, element.html());
                }
            };
        })
        .controller("MyCtrl", function($scope) {
            $scope.color = "something";
        });

我想知道一件事。我们得到了指令&#34; mySelectView&#34;,其中包含&#34; link&#34;功能。这个&#34;链接&#34;功能取决于&#34;观点&#34;要定义的变量并包含某些内容。

获得它的唯一方法是通过调用&#34;链接&#34;在其他指令&#34; myView&#34;上运行。该指令对previous指令有一个require参数。

所以我的问题是:&#34;链接&#34;指令功能&#34; mySelectView&#34;在&#34; link&#34;之后执行指令的功能&#34; myView&#34;。我假设这是因为&#34; ng-option&#34;需要$ scope.views的属性才能正确显示内容。这意味着&#34; myView&#34;的链接功能获得执行并添加视图。

但是怎么样?谁决定这个订单?为什么&#34;链接&#34;由于未定义的$ scope.views,第一个指令的功能不高兴失败?

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

您的$scope.views未定义。相反,它已初始化为空数组$scope.views = [];

我希望这个link能够回答你关于链接功能执行顺序的问题