1
2

More than 5 years have passed since last update.

AngularJS の Directive のコールバック(isolate scope の &)でパラメータを受け取る方法

Posted at

例えばディレクティブ内の非同期処理終了後に、処理結果を受け取って何かをしたい場合はこうする

html
<directive callback="vm.callback(promise)"/>
directive
scope.callback({promise: defer.promise})
defer.resolve(result)

directive 側で指定した JSON のキー名が呼び出し側では引数名になる。

html
<div ng-controller="directiveParamCtrl as vm">
    <directive-param callback="vm.callback(promise)"/>
</div>
directive
angular.module('demo', [])
    .controller('directiveParamCtrl', function(){
        this.callback = function(promise){
            promise.then(function(param){
                console.log(param.time, param.mes) // 3, 3秒経ちました
            })
        }        
    })
    .directive('directiveParam', function($timeout, $q){
        return {
            scope: {
                callback: '&'
            },
            template: '<div>directiveParam</div>',
            link: function(scope,el){
                var s = 3;
                var defer = $q.defer();
                $timeout(function(){
                    var mes = s + '秒経ちました';
                    el.text(mes)
                    defer.resolve({
                        time: s,
                        mes: mes
                    });
                },s * 1000)
                scope.callback({promise: defer.promise})
            }
        }
    });
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2