使用ng-change来选择ng对象。

时间:2021-08-04 10:29:49

Given the following select element

给定以下select元素

<select ng-options="size.code as size.name for size in sizes " 
        ng-model="item.size.code" 
        ng-change="update(MAGIC_THING)">
</select>

Is there a way to get MAGIC_THING to be equal to the currently selected size, so I have access to size.name and size.code in my controller?

是否有办法使MAGIC_THING与当前选定的大小相等,所以我可以访问siz .name和size。我的控制器代码?

size.code affects a lot of the other parts of the app (image urls, etc), but when the ng-model of item.size.code is updated, item.size.name needs to be updated as well for the user facing stuff. I assume that the correct way to do this is capturing the change event and setting the values inside of my controller, but I'm not sure what I can pass into update to get the proper values.

大小。代码会影响应用程序的许多其他部分(图像url等),但是当item.size的ng模型时。代码被更新,item.size.name也需要更新,以供用户使用。我假设正确的方法是捕获更改事件并在我的控制器中设置值,但是我不确定我可以传递什么到update中以获得正确的值。

If this is completely the wrong way to go about it, I'd love to know the right way.

如果这是完全错误的方式,我想知道正确的方式。

10 个解决方案

#1


444  

Instead of setting the ng-model to item.size.code, how about setting it to size:

而不是将ng-model设置为item.size。代码,如何设置它的大小:

<select ng-options="size as size.name for size in sizes" 
   ng-model="item" ng-change="update()"></select>

Then in your update() method, $scope.item will be set to the currently selected item.

然后在update()方法中,使用$scope。项目将被设置为当前选择的项目。

And whatever code needed item.size.code, can get that property via $scope.item.code.

以及任何代码需要的项。size。代码,可以通过$scope.item.code获得该属性。

Fiddle.

小提琴。

Update based on more info in comments:

基于更多的信息更新评论:

Use some other $scope property for your select ng-model then:

然后为您的选择ng-model使用一些其他的$scope属性:

<select ng-options="size as size.name for size in sizes" 
   ng-model="selectedItem" ng-change="update()"></select>

Controller:

控制器:

$scope.update = function() {
   $scope.item.size.code = $scope.selectedItem.code
   // use $scope.selectedItem.code and $scope.selectedItem.name here
   // for other stuff ...
}

#2


56  

You can also directly get selected value using following code

您还可以使用以下代码直接获得所选的值。

 <select ng-options='t.name for t in templates'
                  ng-change='selectedTemplate(t.url)'></select>

script.js

script.js

 $scope.selectedTemplate = function(pTemplate) {
    //Your logic
    alert('Template Url is : '+pTemplate);
}

#3


11  

you also coud try this:

你也可以试试这个:

<select  ng-model="selectedItem" ng-change="update()">
<option ng-repeat="item in items" ng-selected="selectedItem == item.Id" value="{{item.Id}}">{{item.Name}}</option>
</select>

#4


5  

If Divyesh Rupawala's answer doesn't work (passing the current item as the parameter), then please see the onChanged() function in this Plunker. It's using this:

如果Divyesh Rupawala的答案不起作用(将当前项作为参数传递),那么请查看这个柱塞中的onChanged()函数。用这个:

http://plnkr.co/edit/B5TDQJ

http://plnkr.co/edit/B5TDQJ

#5


2  

<select ng-model="item.size.code">
<option ng-repeat="size in sizes" ng-attr-value="size.code">{{size.name}}          </option>
</select>

#6


2  

//Javascript
$scope.update = function () {
    $scope.myItem;
    alert('Hello');
}
<!--HTML-->
<div class="form-group">
     <select name="name"
             id="id" 
             ng-model="myItem" 
             ng-options="size as size.name for size in sizes"
             class="form-control" 
             ng-change="update()"
             multiple
             required>
     </select>
</div>

İf you want to write, name, id, class, multiple, required , You can write in this way.

İf你想写、名称、id、类,多个,必需的,你可以以这种方式编写。

#7


1  

This might give you some ideas

这可能会给你一些建议

.NET C# View Model

net c#视图模型

public class DepartmentViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
}

.NET C# Web Api Controller

。net c# Web Api控制器

public class DepartmentController : BaseApiController
{
    [HttpGet]
    public HttpResponseMessage Get()
    {
        var sms = Ctx.Departments;

        var vms = new List<DepartmentViewModel>();

        foreach (var sm in sms)
        {
            var vm = new DepartmentViewModel()
            {
                Id = sm.Id,
                Name = sm.DepartmentName
            };
            vms.Add(vm);
        }

        return Request.CreateResponse(HttpStatusCode.OK, vms);
    }

}

Angular Controller:

角控制器:

$http.get('/api/department').then(
    function (response) {
        $scope.departments = response.data;
    },
    function (response) {
        toaster.pop('error', "Error", "An unexpected error occurred.");
    }
);

$http.get('/api/getTravelerInformation', { params: { id: $routeParams.userKey } }).then(
   function (response) {
       $scope.request = response.data;
       $scope.travelerDepartment = underscoreService.findWhere($scope.departments, { Id: $scope.request.TravelerDepartmentId });
   },
    function (response) {
        toaster.pop('error', "Error", "An unexpected error occurred.");
    }
);

Angular Template:

角模板:

<div class="form-group">
    <label>Department</label>
    <div class="left-inner-addon">
        <i class="glyphicon glyphicon-hand-up"></i>
        <select ng-model="travelerDepartment"
                ng-options="department.Name for department in departments track by department.Id"
                ng-init="request.TravelerDepartmentId = travelerDepartment.Id"
                ng-change="request.TravelerDepartmentId = travelerDepartment.Id"
                class="form-control">
            <option value=""></option>
        </select>
    </div>
</div>

#8


1  

AngularJS's Filter worked out for me.

AngularJS的过滤器对我来说很有用。

Assuming the code/id is unique, we can filter out that particular object with AngularJS's filter and work with the selected objects properties. Considering the example above:

假设代码/id是唯一的,我们可以使用AngularJS的过滤器过滤特定的对象,并使用所选的对象属性。考虑到上面的例子:

<select ng-options="size.code as size.name for size in sizes" 
        ng-model="item.size.code" 
        ng-change="update(MAGIC_THING); search.code = item.size.code">
</select>

<!-- OUTSIDE THE SELECT BOX -->

<h1 ng-repeat="size in sizes | filter:search:true"
    ng-init="search.code = item.size.code">
  {{size.name}}
</h1>

Now, there are 3 important aspects to this:

这里有三个重要的方面

  1. ng-init="search.code = item.size.code" - on initializing h1 element outside select box, set the filter query to the selected option.

    ng-init = "搜索。代码= item.size。“代码”——在select框外初始化h1元素时,将过滤器查询设置为所选选项。

  2. ng-change="update(MAGIC_THING); search.code = item.size.code" - when you change the select input, we'll run one more line which will set the "search" query to the currently selected item.size.code.

    ng-change = "更新(MAGIC_THING);搜索。代码= item.size。代码“——当您更改select输入时,我们将运行另一行,它将把“搜索”查询设置为当前所选的项。

  3. filter:search:true - Pass true to filter to enable strict matching.

    过滤器:搜索:真-传递真过滤,使严格匹配。

That's it. If the size.code is uniqueID, we'll have only one h1 element with the text of size.name.

就是这样。如果大小。代码是独特的eid,我们将只有一个h1元素的文本大小。name。

I've tested this in my project and it works.

我在我的项目中测试过这个,它很有效。

Good Luck

祝你好运

#9


0  

You need to use "track by" so that the objects can be compared correctly. Otherwise Angular will use the native js way of comparing objects.

您需要使用“track by”来正确地比较对象。否则,角度将使用本机js方式比较对象。

So your example code would change to -

所以你的例子代码会变成-

    <select ng-options="size.code as size.name
 for size in sizes track by size.code" 
ng-model="item.size.code"></select>

#10


0  

This is the cleanest way to get a value from an angular select options list (other than The Id or Text). Assuming you have a Product Select like this on your page :

这是从角选择选项列表(除了Id或文本)获取值的最干净的方法。假设您的页面上有这样的产品选择:

<select ng-model="data.ProductId"
        ng-options="product.Id as product.Name for product in productsList"
        ng-change="onSelectChange()">
</select>

Then in Your Controller set the callback function like so:

然后在控制器中设置回调函数如下:

    $scope.onSelectChange = function () {
        var filteredData = $scope.productsList.filter(function (response) {
            return response.Id === $scope.data.ProductId;
        })
        console.log(filteredData[0].ProductColor);
    }

Simply Explained: Since the ng-change event does not recognize the option items in the select, we are using the ngModel to filter out the selected Item from the options list loaded in the controller.

简单解释:由于ng-change事件不识别select中的选项项,所以我们使用ngModel从控制器中加载的选项列表中筛选所选项。

Furthermore, since the event is fired before the ngModel is really updated, you might get undesirable results, So a better way would be to add a timeout :

此外,由于事件是在ngModel真正更新之前触发的,您可能会得到不希望的结果,所以更好的方法是添加一个超时:

        $scope.onSelectChange = function () {
            $timeout(function () {
            var filteredData = $scope.productsList.filter(function (response) {
                return response.Id === $scope.data.ProductId;
            })
            console.log(filteredData[0].ProductColor);
            }, 100);
        };

#1


444  

Instead of setting the ng-model to item.size.code, how about setting it to size:

而不是将ng-model设置为item.size。代码,如何设置它的大小:

<select ng-options="size as size.name for size in sizes" 
   ng-model="item" ng-change="update()"></select>

Then in your update() method, $scope.item will be set to the currently selected item.

然后在update()方法中,使用$scope。项目将被设置为当前选择的项目。

And whatever code needed item.size.code, can get that property via $scope.item.code.

以及任何代码需要的项。size。代码,可以通过$scope.item.code获得该属性。

Fiddle.

小提琴。

Update based on more info in comments:

基于更多的信息更新评论:

Use some other $scope property for your select ng-model then:

然后为您的选择ng-model使用一些其他的$scope属性:

<select ng-options="size as size.name for size in sizes" 
   ng-model="selectedItem" ng-change="update()"></select>

Controller:

控制器:

$scope.update = function() {
   $scope.item.size.code = $scope.selectedItem.code
   // use $scope.selectedItem.code and $scope.selectedItem.name here
   // for other stuff ...
}

#2


56  

You can also directly get selected value using following code

您还可以使用以下代码直接获得所选的值。

 <select ng-options='t.name for t in templates'
                  ng-change='selectedTemplate(t.url)'></select>

script.js

script.js

 $scope.selectedTemplate = function(pTemplate) {
    //Your logic
    alert('Template Url is : '+pTemplate);
}

#3


11  

you also coud try this:

你也可以试试这个:

<select  ng-model="selectedItem" ng-change="update()">
<option ng-repeat="item in items" ng-selected="selectedItem == item.Id" value="{{item.Id}}">{{item.Name}}</option>
</select>

#4


5  

If Divyesh Rupawala's answer doesn't work (passing the current item as the parameter), then please see the onChanged() function in this Plunker. It's using this:

如果Divyesh Rupawala的答案不起作用(将当前项作为参数传递),那么请查看这个柱塞中的onChanged()函数。用这个:

http://plnkr.co/edit/B5TDQJ

http://plnkr.co/edit/B5TDQJ

#5


2  

<select ng-model="item.size.code">
<option ng-repeat="size in sizes" ng-attr-value="size.code">{{size.name}}          </option>
</select>

#6


2  

//Javascript
$scope.update = function () {
    $scope.myItem;
    alert('Hello');
}
<!--HTML-->
<div class="form-group">
     <select name="name"
             id="id" 
             ng-model="myItem" 
             ng-options="size as size.name for size in sizes"
             class="form-control" 
             ng-change="update()"
             multiple
             required>
     </select>
</div>

İf you want to write, name, id, class, multiple, required , You can write in this way.

İf你想写、名称、id、类,多个,必需的,你可以以这种方式编写。

#7


1  

This might give you some ideas

这可能会给你一些建议

.NET C# View Model

net c#视图模型

public class DepartmentViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
}

.NET C# Web Api Controller

。net c# Web Api控制器

public class DepartmentController : BaseApiController
{
    [HttpGet]
    public HttpResponseMessage Get()
    {
        var sms = Ctx.Departments;

        var vms = new List<DepartmentViewModel>();

        foreach (var sm in sms)
        {
            var vm = new DepartmentViewModel()
            {
                Id = sm.Id,
                Name = sm.DepartmentName
            };
            vms.Add(vm);
        }

        return Request.CreateResponse(HttpStatusCode.OK, vms);
    }

}

Angular Controller:

角控制器:

$http.get('/api/department').then(
    function (response) {
        $scope.departments = response.data;
    },
    function (response) {
        toaster.pop('error', "Error", "An unexpected error occurred.");
    }
);

$http.get('/api/getTravelerInformation', { params: { id: $routeParams.userKey } }).then(
   function (response) {
       $scope.request = response.data;
       $scope.travelerDepartment = underscoreService.findWhere($scope.departments, { Id: $scope.request.TravelerDepartmentId });
   },
    function (response) {
        toaster.pop('error', "Error", "An unexpected error occurred.");
    }
);

Angular Template:

角模板:

<div class="form-group">
    <label>Department</label>
    <div class="left-inner-addon">
        <i class="glyphicon glyphicon-hand-up"></i>
        <select ng-model="travelerDepartment"
                ng-options="department.Name for department in departments track by department.Id"
                ng-init="request.TravelerDepartmentId = travelerDepartment.Id"
                ng-change="request.TravelerDepartmentId = travelerDepartment.Id"
                class="form-control">
            <option value=""></option>
        </select>
    </div>
</div>

#8


1  

AngularJS's Filter worked out for me.

AngularJS的过滤器对我来说很有用。

Assuming the code/id is unique, we can filter out that particular object with AngularJS's filter and work with the selected objects properties. Considering the example above:

假设代码/id是唯一的,我们可以使用AngularJS的过滤器过滤特定的对象,并使用所选的对象属性。考虑到上面的例子:

<select ng-options="size.code as size.name for size in sizes" 
        ng-model="item.size.code" 
        ng-change="update(MAGIC_THING); search.code = item.size.code">
</select>

<!-- OUTSIDE THE SELECT BOX -->

<h1 ng-repeat="size in sizes | filter:search:true"
    ng-init="search.code = item.size.code">
  {{size.name}}
</h1>

Now, there are 3 important aspects to this:

这里有三个重要的方面

  1. ng-init="search.code = item.size.code" - on initializing h1 element outside select box, set the filter query to the selected option.

    ng-init = "搜索。代码= item.size。“代码”——在select框外初始化h1元素时,将过滤器查询设置为所选选项。

  2. ng-change="update(MAGIC_THING); search.code = item.size.code" - when you change the select input, we'll run one more line which will set the "search" query to the currently selected item.size.code.

    ng-change = "更新(MAGIC_THING);搜索。代码= item.size。代码“——当您更改select输入时,我们将运行另一行,它将把“搜索”查询设置为当前所选的项。

  3. filter:search:true - Pass true to filter to enable strict matching.

    过滤器:搜索:真-传递真过滤,使严格匹配。

That's it. If the size.code is uniqueID, we'll have only one h1 element with the text of size.name.

就是这样。如果大小。代码是独特的eid,我们将只有一个h1元素的文本大小。name。

I've tested this in my project and it works.

我在我的项目中测试过这个,它很有效。

Good Luck

祝你好运

#9


0  

You need to use "track by" so that the objects can be compared correctly. Otherwise Angular will use the native js way of comparing objects.

您需要使用“track by”来正确地比较对象。否则,角度将使用本机js方式比较对象。

So your example code would change to -

所以你的例子代码会变成-

    <select ng-options="size.code as size.name
 for size in sizes track by size.code" 
ng-model="item.size.code"></select>

#10


0  

This is the cleanest way to get a value from an angular select options list (other than The Id or Text). Assuming you have a Product Select like this on your page :

这是从角选择选项列表(除了Id或文本)获取值的最干净的方法。假设您的页面上有这样的产品选择:

<select ng-model="data.ProductId"
        ng-options="product.Id as product.Name for product in productsList"
        ng-change="onSelectChange()">
</select>

Then in Your Controller set the callback function like so:

然后在控制器中设置回调函数如下:

    $scope.onSelectChange = function () {
        var filteredData = $scope.productsList.filter(function (response) {
            return response.Id === $scope.data.ProductId;
        })
        console.log(filteredData[0].ProductColor);
    }

Simply Explained: Since the ng-change event does not recognize the option items in the select, we are using the ngModel to filter out the selected Item from the options list loaded in the controller.

简单解释:由于ng-change事件不识别select中的选项项,所以我们使用ngModel从控制器中加载的选项列表中筛选所选项。

Furthermore, since the event is fired before the ngModel is really updated, you might get undesirable results, So a better way would be to add a timeout :

此外,由于事件是在ngModel真正更新之前触发的,您可能会得到不希望的结果,所以更好的方法是添加一个超时:

        $scope.onSelectChange = function () {
            $timeout(function () {
            var filteredData = $scope.productsList.filter(function (response) {
                return response.Id === $scope.data.ProductId;
            })
            console.log(filteredData[0].ProductColor);
            }, 100);
        };