angularjsasp.net-mvc-4angularjs-ng-change

ng-change not working in Select


I don't know what happen but this function seems like not working at all.

Here is my view:

<tr>
    <th>Category</th>
    <td>
       <select class="form-control" ng-model="masterlist.category_id" ng-options="c.category_id as c.category_name for c in category" required data-ng-change="getSubCategory(c.category_id)"></select>
    </td>
</tr>
<tr>
     <th>Sub Category</th>
     <td>
                                                <select class="form-control" ng-model="masterlist.sub_category_id" ng-options="c.sub_category_id as c.sub_category_name for c in subCategory" required></select>
     </td>
</tr>

Angular JS

$scope.getSubCategory = function (category_id) {
        $http.get('/MasterList/SubCategory' + category_id).then(function ($response) {
            $scope.subCategory = $response.data;
        });
    }

Controller:

public ActionResult SubCategory(int id)
        {
            db.Configuration.ProxyCreationEnabled = false;
            return Json(db.Sub_Category.Where(x => x.active_flag == true && x.category_id == id).ToList(), JsonRequestBehavior.AllowGet);
        }

I check on the console but nothing's error and here is the inspect element view:

enter image description here

My main goal is to once category is selected, the display for sub category will be only those under the category.

Thanks in advance for the help.


Solution

  • Your select element's ng-model is set to masterlist.category_id. So you should pass that to your getSubCategory method.

    <select class="form-control" ng-model="masterlist.category_id"
            ng-options="c.category_id as c.category_name for c in vm.category" 
            required data-ng-change="vm.getSubCategory(masterlist.category_id)"></select>
    

    Also you need to send a request with the url pattern SubCategory/3 where 3 is the category id value. With your current code it is going to make a request to SubCategory3 and you will see a 404 error if you inpsect your browser network tab.

    You should add a / between the catetory_id variable and the action method name,

    $http.get('Home/SubCategory/' + category_id)
    

    I also recommend moving your http calls to a data service which can be injeccted to your controller. Als, you should not hard code the url's like that in your js file. Try to use the Url.Action helper method to generate the proper relative urls to your action method/api endpoints as explained in this post and this post.