Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
855 views
in Technique[技术] by (71.8m points)

angularjs - Populate Dropdown 2 based on Dropdown 1 selection

I am able to populate 2 dropdowns directly from database. My problem is, the 2nd dropdown values has to be populated based on the 1st dropdown selection. Since i am new to Angular, i m not able to figure that out, can someone help me out with this.

<select id="OfficeId" name="OfficeId" ng-model="item.OfficeId"
        ng-options="item.OfficeId as item.OfficeName for item in Offices">
    <option value="" selected>Select the Office</option>
</select>
<select id="OBJ" name="OBJ" ng-model="item.OfficeOBJId"
        ng-options="item.OfficeOBJId as item.OBJId for item in Codes">
    <option value="" selected>Select OBJ Code</option>
</select>

myApp.factory('OfficeNames', function ($resource) {
    return $resource(
        'api/Office/:id',
        { id: '@id' },
        { update: { method: 'PUT' } }
    );
});     

myApp.factory('OfficeObjCode', function ($resource) {
    return $resource(
        'api/OfficeObj/:id',
        { id: '@id' },
        { update: { method: 'PUT' } }
    );
});

function OfficeCtrl($scope, $location, OfficeNames) {
    $scope.Offices = OfficeNames.query();
}

function OfficeObjCtrl($scope, $location, OfficeObjCode) {
    $scope.Codes = OfficeObjCode.query();
}

Note: I am using Web API/Angular/Petapoco/SQL Server

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You shouldn't need 2 controllers for this, in fact that is probably one of the problems. Once they are within the same scope you can easily tie them together. Use ng-change on the first option to trigger a function that gets the values to populate the second option.

Example Fiddle: http://jsfiddle.net/TheSharpieOne/Xku9z/

Also, you can use ng-show with the second select's options array length to only show the second select when it has been populated.

Example Fiddle: http://jsfiddle.net/TheSharpieOne/Xku9z/1/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...