ng-change 在 Select 中不起作用

ng-change not working in Select

我不知道发生了什么,但这个功能似乎根本不起作用。

这是我的观点:

<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;
        });
    }

控制器:

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);
        }

我检查了控制台,但没有任何错误,这是检查元素视图:

我的主要目标是一旦选择了类别,子类别的显示将只显示该类别下的内容。

在此先感谢您的帮助。

您的 select 元素的 ng-model 设置为 masterlist.category_id。所以你应该把它传递给你的 getSubCategory 方法。

<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>

您还需要使用 url 模式 SubCategory/3 发送请求,其中 3 是类别 ID 值。使用您当前的代码,它将向 SubCategory3 发出请求,如果您检查浏览器网络选项卡,您将看到 404 错误。

您应该在 catetory_id 变量和操作方法名称之间添加一个 /

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

我还建议将您的 http 调用移动到可以注入到您的控制器的数据服务。另外,你不应该在你的 js 文件中硬编码 url。尝试使用 Url.Action 辅助方法为您的操作 method/api 端点生成正确的相对 urls,如 this post 和此 post.[=17 中所述=]