AngularJS推项目$范围数组的第一个或0指数 [英] AngularJS push item to first or 0 index of $scope array

查看:129
本文介绍了AngularJS推项目$范围数组的第一个或0指数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮我实现这个功能。我有一个项目在我的 $范围数组。现在,当我点击Add Item按钮,我想一个新的项目推到第一个索引或0索引数组。提前致谢。 :)

下面是一个工作的的jsfiddle 以开始: http://jsfiddle.net/limeric29/ 7FH2e /

HTML:

 < D​​IV NG控制器=CTRL>
    {{}数据}< BR />
    <输入类型=按钮NG点击=的addItem()VALUE =添加项目/>
< / DIV>

JavaScript的:

 功能Ctrl键($范围){
    $ scope.data = [
    新的String(第5项),新的String(项目4),新的String(项目3),新的String(项目2),新的String(项目1')];    $ scope.addItem =功能(){
        变种C = $ scope.data.length + 1;
        VAR项目=新的String('项目'+ C)
        $ scope.data.push(项目);
    };
}


解决方案

通过剪接()来代替push()和分配给插入什么数组索引解决了我的问题。

HTML:

 < D​​IV NG控制器=CTRL>
    < pre> {{}数据}< / pre>< BR />
    <输入类型=按钮NG点击=的addItem()VALUE =添加项目/>
< / DIV>

的Javascript:

 功能Ctrl键($范围){
    $ scope.data = [
    新的String(项目4),新的String(项目3),新的String(项目2),新的String(项目1')];    $ scope.addItem =功能(){
        变种C = $ scope.data.length + 1;
        VAR项目=新的String('项目'+ C)
        $ scope.data.splice(0,0,项目);
    };
}

下面是更新后的小提琴这一点。 http://jsfiddle.net/limeric29/xvHNe/

Please help me implement this function. I have an array of items in my $scope. Now, when I click on the Add Item button, I want to push a new item to the first index or 0 index of that array. Thanks in advance. :)

Here's a working jsFiddle to start with: http://jsfiddle.net/limeric29/7FH2e/

HTML:

<div ng-controller="Ctrl">
    {{data}}<br/>
    <input type="button" ng-click="addItem()" value="Add Item" />
</div>

JavaScript:

function Ctrl($scope) {
    $scope.data = [
    new String('Item 5'), new String('Item 4'), new String('Item 3'), new String('Item 2'), new String('Item 1')];

    $scope.addItem = function () {
        var c = $scope.data.length + 1;
        var item = new String('Item ' + c)
        $scope.data.push(item);
    };
}

解决方案

Solved my problem by using splice() instead of push() and assigning to what array index to insert.

HTML:

<div ng-controller="Ctrl">
    <pre>{{data}}</pre><br/>
    <input type="button" ng-click="addItem()" value="Add Item" />
</div>

Javascript:

function Ctrl($scope) {
    $scope.data = [
    new String('Item 4'), new String('Item 3'), new String('Item 2'), new String('Item 1')];

    $scope.addItem = function () {
        var c = $scope.data.length + 1;
        var item = new String('Item ' + c)
        $scope.data.splice(0, 0, item);
    };
}

Here's the updated fiddle for this. http://jsfiddle.net/limeric29/xvHNe/

这篇关于AngularJS推项目$范围数组的第一个或0指数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆