简体   繁体   中英

How can I send to angular directive reference of model, not copy

I use directive like this :

.directive('inputExtended', function() {
        //input with extra expression, when expression is true in right side we show success image, else we show error image
        // use this directive in <form>
        return {
            restrict: 'E',
            templateUrl: 'templates/input-extended.html',
            replace: true,
            scope: {
                success: '=success',
                error: '=error',
                inputModel: '=inputModel',
                value: '=value',
                name: '=name'
            }
        }
    })

I use this directive like this :

<input-extended name="'username'" inputModel="LoginCtrl.username" value="'username' | translate" success="!form.username.$error.required && form.username.$dirty" error="form.username.$error.required && form.username.$dirty"></input-extended>

Directive code:

<div>
<input ng-click="test()" type="text" name="{{name}}" ng-model="inputModel" placeholder="{{value}}" required />
<div class="error" ng-if="error">
    <img src="../img/error.png">
</div>
<div class="success" ng-if="success">
    <img src="../img/success.png">
</div>

But when I use this directive, to directive angular dont send original refernce to LoginCtrl.username. How can I send original reference ?

By doing this :

        scope: {
            success: '=success',
            error: '=error',
            inputModel: '=inputModel',
            value: '=value',
            name: '=name'
        }

You create a new isolated scope, which copies the objects and add watches on both scopes (parent and child) to handle bidirectional binding.

Unfortunately you can't pass the reference of your object to a new isolated scope. What you can do, is storing the variable into a service, then giving your directive some parameters to retrieve the variable.

eg :

directive :

service-name="loginService" service-method="getLoginInfo"

add this in your scope :

        scope: {
            success: '=success',
            error: '=error',
            inputModel: '=inputModel',
            value: '=value',
            name: '=name'
            serviceName: '@',
            serviceMethod: '@'
        }

And then, into a controller :

    return {
        restrict: 'E',
        templateUrl: 'templates/input-extended.html',
        replace: true,
        scope: {
            //
        },
        controller: ["$injector", function($injector){
            var service = $injector.get($scope.serviceName);
            $scope.someObject = service[$scope.serviceMethod]();
        }]
    };

but I don't like this at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM