0

I have several instances of specific directive like that:

<type="text" my-directive ng-model="formData.property1">
<type="text" my-directive ng-model="formData.property2">

formData.propery is an object like { name: '', code: '' }. formData.propery.name is used in view layer and formData.propery.code is sent to the server as value.

I want to init these directives from URL parameters - pass codes and get whole object as model value.

The difficulties here are:

  1. I can't call function in directive scope that gets object from server with specific code, because it violates separation of concerns of parent scope and directive scope.

  2. I can't init models from parent scope because of asyncronous call type of $http request.

  3. I can't use specific init function in directive that gets object from server by model variable name because it a bit awkward and mess the code.

So what is proper way to do that?

Example 1:

    getObj1 = (code)->
        $http({
            url: '/api/service/GetByCode'
            method: 'POST'
            data: { code: code }
            headers: {'Content-Type': 'application/json; charset=utf-8'}
        })
        .success((data)->
            $scope.formData.property1 = angular.fromJson(data.result)
        )

    getObj2 = (code)->
        $http({
            url: '/api/service/GetByCode'
            method: 'POST'
            data: { code: code }
            headers: {'Content-Type': 'application/json; charset=utf-8'}
        })
        .success((data)->
            $scope.formData.property2 = angular.fromJson(data.result)
        )

1 Answer 1

0

Well, I've just needed to pass property to assign as argument to function using closure:

   getObj = (code, prop)->
        theProp = prop
        $http({
            url: '/api/service/GetByCode'
            method: 'POST'
            data: { code: code }
            headers: {'Content-Type': 'application/json; charset=utf-8'}
        })
        .success((data)->
            theProp = angular.fromJson(data.result)
        )

and then call it like this:

getObj(someCode1, scope.formData.property1)
getObj(someCode2, scope.formData.property2) 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.