离子事件不会在指令内部触发

时间:2016-09-13 06:44:35

标签: angularjs ionic-framework ionic-view

我希望在视图加载后/进入该视图后执行一个函数。

我的目录如下:

app.directive('bonFormViewerFrame', function ($formStore) {
return {
    restrict: 'E', //bind to element tag name
    replace: true, //replace the entire markup with the template
    templateUrl: 'ui/controls/bon-form-viewer-frame.html',
    scope: {
        form: '=' //specifies the item to be displayed.
    },
    controller: ['$scope', function ($scope) {

        $scope.formContent = ($scope.form != null) ? $scope.form.Content : "";

        $scope.$on("$ionicView.beforeEnter", function (event, data) {
            // handle event
            console.log("State Params: ", data.stateParams);
        });

        $scope.$on("$ionicView.enter", function (event, data) {
            // handle event
            console.log("State Params: ", data.stateParams);
        });

        $scope.$on("$ionicView.afterEnter", function (event, data) {
            // handle event
            console.log("State Params: ", data.stateParams);
        });


    }]
};

});

以上$ionicView事件均未触发。谁能帮我吗?或者我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

  

上述$ ionicView事件均未触发。

好吧,如果您检查ionic.bundle.js,可以找到以下行:

enteringScope.$emit('$ionicView.enter', enteringData);
enteringScope.$broadcast('$ionicParentView.enter', enteringData);

对于参考:

  • $ broadcast - 将事件向下调度到所有子范围,
  • $ emit - 通过范围层次结构向上调度事件。

$ionicView使用$emit

问题是,你的指令有不同的范围 - 你的主控制器的孩子

所以你需要$ionicParentView a.e。:

$scope.$on("$ionicParentView.beforeEnter", function (event, data) {
     // ...

});

Demo Plunker

结果:

~+~+~ CTRL~+~+~ 
CTRL: on beforeEnter
~+~+~ DIR ~+~+~
CTRL: on enter
DIR: on enter
CTRL: on afterEnter
DIR: on afterEnte

但是,如果你的指令加载延迟而离子在指令控制器重新发送到事件之前广播这些事件 - 你与它无关