Two way data binding in AngularJS Directives

前端 未结 3 1780
情深已故
情深已故 2020-12-08 10:10

I have been trying to define directives so I can display different \"widgets\" in a form, depending on the type of field and its parameters, which are stored in a database.

3条回答
  •  伪装坚强ぢ
    2020-12-08 10:44

    Here's a way to pass to a callback parameter in a directive. The controller template:

        
    

    The directive:

    angular.module('component')
        .directive('componentPagingSelectDirective', [
            function( ) {
                return {
                    restrict: 'E',
                    scope: { 
                        // using the '=' for two way doesn't work
                        pageItemLimit:  '@', // the '@' is one way from controller
                        pageChangeHandler: '&'
                    },
                    controller: function($scope) {   
                        // pass value from this scope to controller method. 
                        // controller method will update the var in controller scope
                        $scope.pageChangeHandler({
                            paramPulledOutOffThinAir: $scope.pageItemLimit
                        })
    
                    }, ...
    

    In the controller:

    angular.module('...').controller(...
            $scope.pageItemLimit = 0; // initial value for controller scoped var
    
            // complete the data update by setting the var in controller scope 
            // to the one from the directive
            $scope.pageChangeHandler = function(paramPulledOutOffThinAir) {
                $scope.pageItemLimit = paramPulledOutOffThinAir;
            }
    

    Note the difference in function parameters for the directive (an object with parameter as keys), template ('unwrapped' keys from the parameter object in directive), and controller definition.

提交回复
热议问题