2012-12-14 30 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);