2017-08-11 54 views
1

我有一個由少數已知輸入和少數部分組成的表單,這些部分是我無法控制的,但可以期望被正確書寫。簡化它看起來像這樣:角度 - 在引導程序中提取指令的屬性值

<form ...> 
    <input name="input1" type="hidden" value="1"> 
    <div class="from_partial" ng-controller="Controller"> 
    <!-- here goes first partial --> 
    <button type="button" ng-click="check()">Check</button> 
    </div> 
    <div class="from_partial" ng-controller="Controller"> 
    <!-- here goes second partial --> 
    <button type="button" ng-click="check()">Check</button> 
    </div> 
</form> 

部分看起來像這樣:

<div class="item"> 
    <input type="text" ng-model="name"/> 
</div> 
<div class="item"> 
    <input type="text" ng-model="age"/> 
</div> 

現在我需要在控制器的check()功能以某種方式使用這些輸入,分別爲每個部分。我不知道他們的名字。列舉它們的最好方法是什麼?是否有可能獲得他們(即找到他們的名字),而Angular是自舉和連接$scope的特定模型?

換句話說,我想每個Controller對象知道輸入的名稱,例如$scope.input_names包含{"name", "age"}

+0

如果表單有一個「名稱」屬性,你可以得到它是'$ scope.formName'對象中的所有模型。 –

回答

0

事實證明這是可以定義具有相同名稱的多個指令和與此變得容易:

angular.module(app_name) 
.controller("Controller", ['$scope', function ($scope) { 
    $scope.input_names = []; 
    ... 
}]) 
.directive('ngModel', function() { 
    var linker = function(scope, element, attrs) { 
     scope.input_names.push(attrs.ngModel); 
    } 

    return { 
     restrict: 'A', 
     priority: 100, 
     require: '?ngModel', 
     link: linker 
    }; 
}); 

原角指令優先1定義,將得到優先執行。然後,自定義指令將插入使用ng-model屬性定義的名稱到scope.input_names。這確保每個控制器只會獲取在相關部分中定義的名稱。與ng-model相關的所有其他內容將照常工作。