2012-12-14 36 views
0

我有一个包含元素名称的输入字符串(我的意思是“name”属性)。 如何搜索具有给定名称的元素的$ scope?Angular.js - 元素的搜索范围

我想要做的就是让一个参数化指令

<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> 

目前在CoffeeScript中的代码如下所示:

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 

我想摆脱switch语句并搜索元素与名称== attrs ['bindslave']

回答

0

我还不确定你要完成什么,但为什么不用你的开关替换这样的东西:

scope[attrs.bindslave] = viewValue 

,然后用正确的引用上的HTML:

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

我更新的问题。如果你的回答仍然适用于此,请告诉我。 – Paul

2

如何搜索$范围是否与给定的名称元素?

给你的表单一个名字,然后Angular将FormController发布到给定名称下的当前作用域。如果你的表单元素都有名字,他们也提供:

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

然后你就可以访问有关表单元素的信息:

console.log($scope.myForm.billing_state, $scope.myForm.shipping_state);