2016-09-01 149 views
0

我有一個包含以下兩個街區Web表單:傳遞範圍變量到NG-包括

<div class="mm-FilterRow"> 
    <div>First Name:</div> 
    <div><i ng-hide="user.FirstName">Loading...</i><select ng-show="choices.FirstNames" ng-model="user.FirstName" ng-options="o as o for o in choices.FirstNames"></select></div> 
</div> 
<div class="mm-FilterRow"> 
    <div>Last Name:</div> 
    <div><i ng-hide="user.LastName">Loading...</i><select ng-show="choices.LastNames" ng-model="user.LastName" ng-options="o as o for o in choices.LastNames"></select></div> 
</div> 

正如你可以看到,這兩個之間的唯一區別是範圍變量「user.FirstName|user.LastName"和選擇選項「choices.FirstNames|choices.LastNames

因爲我有大約10 div的相同結構的,我想這樣做:(這是僞代碼,非工作)

<div ng-include="singlerow.html" caption="First name" scopetarget="user.FirstName" scopeSource="choices.FirstNames"> 
<div ng-include="singlerow.html" caption="Last name" scopetarget="user.LastName" scopeSource="choices.LastNames"> 

有沒有機會實現我想要的?或者我必須保留那些醜陋的複製/粘貼變體?

回答

1

這是不可能的,在這種情況下更好使用directives

angular.module('DirectiveExample', []) 
 
.controller('Controller', ['$scope', function($scope) { 
 
    $scope.options = [1, 2, 3]; 
 
    $scope.field = "Test"; 
 
}]) 
 
.directive('singlerow', function() { 
 
    return { 
 
    restrict: 'E', 
 
    scope: { 
 
     field: '=', 
 
     options: '=', 
 
    }, 
 
    templateUrl: '/singlerow.html' 
 
    }; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="DirectiveExample"> 
 
<script type="text/ng-template" id="/singlerow.html"> 
 
    <div class="mm-FilterRow"> 
 
    <div>Last Name:</div> 
 
    <div><i ng-hide="field">Loading...</i><select ng-show="options" ng-model="field" ng-options="o as o for o in options"></select></div> 
 
</div> 
 
</script> 
 

 
    <div ng-controller="Controller"> 
 
    <singlerow field="field" options="options"></singlerow> 
 
    </div> 
 
</div>