0

I have an input string containing element's name (I mean the "name" attribute). How to search $scope for element with given name?

What I want to do is to make a parametrized directive

<select bindslave="shipping_state" name="billing_state" ng-model="order.billing_state" ng-options="i.name for i in billingRegions" value="{{ order.billing_state.id }}"></select>
<select name="shipping_state" ng-model="order.shipping_state" ng-options="i.name for i in shippingRegions" value="{{ order.shipping_state.id }}"></select>

Currently the code in CoffeeScript looks like this:

app_directives.directive "bindslave", ->
  require: "ngModel"
  link: (scope, element, attrs, ctrl) ->
    ctrl.$parsers.unshift (viewValue) ->
      if scope.sameAsBilling
        switch attrs['bindslave']
          when "shipping_state"
            scope.order.shipping_state = viewValue
          when "shipping_country"
            scope.order.shipping_country = viewValue
      viewValue

I want to get rid of switch statement and search for an element with name==attrs['bindslave']

2 Answers 2

2

How to search $scope for element with given name?

Give your form a name, then Angular will publish the FormController onto the current scope under the given name. If your form elements have names, they are available also:

<form name="myForm" novalidate>
<select bindslave="shipping_state" name="billing_state" ...>
<select name="shipping_state" ...> 

Then you can access information about the form elements:

console.log($scope.myForm.billing_state, $scope.myForm.shipping_state);
Sign up to request clarification or add additional context in comments.

Comments

0

I'm still not sure what you are trying to accomplish, but why don't you replace your switch with something like this:

scope[attrs.bindslave] = viewValue

and then use the proper reference on the HTML:

<select bindslave="order.shipping_state" ... ></select>

1 Comment

I updated the question. If what you answered still applies to it, please let me know.

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.