AngularJS:使用相同的控制器进行转换

时间:2015-06-30 11:34:17

标签: javascript angularjs angularjs-directive

我有一个包含另一个这样的指令:

<div direction from="origin" to="destination">
    <div direction-map line-color="#e84c3d"></div>
</div>

direction-map指令被转换,请参阅我的代码(Fiddle available here):

var directionController = function() {
    //do stuffs
};
var directionMapController = function() {
    //do other stuffs
};
var Direction = angular.module("direction", [])
    .controller("directionController", directionController)
    .controller("directionMapController", directionMapController)
    .directive("direction", function() {
        var directive = {
            restrict: "AEC",
            controller: "directionController",
            scope: {},
            transclude: true,
            link: {
                pre: function($scope, $element, attrs, controller, transclude) {
                    console.log("direction's controller is directionController : ");
                    console.log(controller.constructor === directionController);//true, that's ok
                    transclude($scope, function(clone) {
                        $element.append(clone);
                    });
                }
            }
        };
        return directive;
    })
    .directive("directionMap", function() {
        var directive = {
            require: "^direction",
            controller: "directionMapController",
            restrict: "AEC",
            scope: true,
            link: {
                pre: function($scope, $element, $attrs, controller) {
                    console.log("directionMap's controller is directionMapController :");
                    console.log(controller.constructor===directionMapController);//false that's not OK!!!!
                }
            }
        };
        return directive;
    });

所以我的问题是:

为什么我的子指令direction-map作为其父级控制器的参数(我认为是因为它被转换),是否可以避免这种情况,或者我应该重新考虑我的代码?

1 个答案:

答案 0 :(得分:1)

它正在发生,因为你使用require: "^direction"如果删除这一行,该指令将获得自己的控制器而不是父控制器。

希望有所帮助:)

更新了Fiddle