Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/463.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用AngularJS跟踪和统计点击次数,并发布到MongoDB_Javascript_Jquery_Angularjs_Mongodb_Mongoose - Fatal编程技术网

Javascript 使用AngularJS跟踪和统计点击次数,并发布到MongoDB

Javascript 使用AngularJS跟踪和统计点击次数,并发布到MongoDB,javascript,jquery,angularjs,mongodb,mongoose,Javascript,Jquery,Angularjs,Mongodb,Mongoose,我希望能够跟踪用户对某个项目的点击,并让它更新与之关联的JSON对象,并显示所有点击次数。我知道如何创建和删除一个对象,但如何在用户单击和相应的投票按钮时添加新名称和值并更新对象?我们将非常感谢您的帮助,并提前向您表示感谢 HTML <body ng-controller="mainController"> <div class="table-responsive"> <table class="table"> &l

我希望能够跟踪用户对某个项目的点击,并让它更新与之关联的JSON对象,并显示所有点击次数。我知道如何创建和删除一个对象,但如何在用户单击和相应的投票按钮时添加新名称和值并更新对象?我们将非常感谢您的帮助,并提前向您表示感谢

HTML

<body ng-controller="mainController">
<div class="table-responsive">
          <table class="table">
            <tr>
                <td>Vote</td>
                <td>Song</td>
                <td>Edit</td>
            </tr>
            <tr ng-repeat="todo in todos">
                <td><button class="btn btn-success icon-thumbs-up" alt="Up vote this song if you like it.">Vote</button></td>
                <td>{{ todo.text }}</td>
                <td><button class="btn btn-danger fa fa-times" ng-click="deleteTodo(todo._id)" alt="Remove the song if you need to make an edit and then add it back."></button></td>
            </tr>
          </table>
        </div>
</body>
服务

angular.module('todoService', [])

// super simple service
// each function returns a promise object 
.factory('Todos', function($http) {
    return {
        get : function() {
            return $http.get('/api/todos');
        },
        create : function(todoData) {
            return $http.post('/api/todos', todoData);
        },
        delete : function(id) {
            return $http.delete('/api/todos/' + id);
        }
    }
});
服务器端角度

var Todo = require('./models/todo');

module.exports = function(app) {

// api ---------------------------------------------------------------------
// get all todos
app.get('/api/todos', function(req, res) {

    // use mongoose to get all todos in the database
    Todo.find(function(err, todos) {

        // if there is an error retrieving, send the error. nothing after res.send(err) will execute
        if (err)
            res.send(err)

        res.json(todos); // return all todos in JSON format
    });
});

// create todo and send back all todos after creation
app.post('/api/todos', function(req, res) {

    // create a todo, information comes from AJAX request from Angular
    Todo.create({
        text : req.body.text,
        done : false
    }, function(err, todo) {
        if (err)
            res.send(err);

        // get and return all the todos after you create another
        Todo.find(function(err, todos) {
            if (err)
                res.send(err)
            res.json(todos);
        });
    });

});

// delete a todo
app.delete('/api/todos/:todo_id', function(req, res) {
    Todo.remove({
        _id : req.params.todo_id
    }, function(err, todo) {
        if (err)
            res.send(err);

        // get and return all the todos after you create another
        Todo.find(function(err, todos) {
            if (err)
                res.send(err)
            res.json(todos);
        });
    });
});

// application -------------------------------------------------------------
app.get('*', function(req, res) {
    res.sendfile('./public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});
angular.module('todoController', [])

// inject the Todo service factory into our controller
.controller('mainController', function($scope, $http, Todos) {
    $scope.formData = {};
    $scope.loading = true;

    // GET =====================================================================
    // when landing on the page, get all todos and show them
    // use the service to get all the todos
    Todos.get()
        .success(function(data) {
            $scope.todos = data;
            $scope.loading = false;
        });

    // CREATE ==================================================================
    // when submitting the add form, send the text to the node API
    $scope.createTodo = function() {
        $scope.loading = true;

        if ($scope.formData.text != undefined) {

            // call the create function from our service (returns a promise object)
        Todos.create($scope.formData)

            // if successful creation, call our get function to get all the new todos
            .success(function(data) {
                $scope.loading = false;
                $scope.formData = {}; // clear the form so our user is ready to enter another
                $scope.todos.unshift(data); // assign our new list of todos
                });
            }
        };

    // DELETE ==================================================================
    // delete a todo after checking it
    $scope.deleteTodo = function(id) {
        $scope.loading = true;

        Todos.delete(id)
            // if successful creation, call our get function to get all the new todos
            .success(function(data) {
                $scope.loading = false;
                $scope.todos = data; // assign our new list of todos
            });
    };

});
})

客户端角度

var Todo = require('./models/todo');

module.exports = function(app) {

// api ---------------------------------------------------------------------
// get all todos
app.get('/api/todos', function(req, res) {

    // use mongoose to get all todos in the database
    Todo.find(function(err, todos) {

        // if there is an error retrieving, send the error. nothing after res.send(err) will execute
        if (err)
            res.send(err)

        res.json(todos); // return all todos in JSON format
    });
});

// create todo and send back all todos after creation
app.post('/api/todos', function(req, res) {

    // create a todo, information comes from AJAX request from Angular
    Todo.create({
        text : req.body.text,
        done : false
    }, function(err, todo) {
        if (err)
            res.send(err);

        // get and return all the todos after you create another
        Todo.find(function(err, todos) {
            if (err)
                res.send(err)
            res.json(todos);
        });
    });

});

// delete a todo
app.delete('/api/todos/:todo_id', function(req, res) {
    Todo.remove({
        _id : req.params.todo_id
    }, function(err, todo) {
        if (err)
            res.send(err);

        // get and return all the todos after you create another
        Todo.find(function(err, todos) {
            if (err)
                res.send(err)
            res.json(todos);
        });
    });
});

// application -------------------------------------------------------------
app.get('*', function(req, res) {
    res.sendfile('./public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});
angular.module('todoController', [])

// inject the Todo service factory into our controller
.controller('mainController', function($scope, $http, Todos) {
    $scope.formData = {};
    $scope.loading = true;

    // GET =====================================================================
    // when landing on the page, get all todos and show them
    // use the service to get all the todos
    Todos.get()
        .success(function(data) {
            $scope.todos = data;
            $scope.loading = false;
        });

    // CREATE ==================================================================
    // when submitting the add form, send the text to the node API
    $scope.createTodo = function() {
        $scope.loading = true;

        if ($scope.formData.text != undefined) {

            // call the create function from our service (returns a promise object)
        Todos.create($scope.formData)

            // if successful creation, call our get function to get all the new todos
            .success(function(data) {
                $scope.loading = false;
                $scope.formData = {}; // clear the form so our user is ready to enter another
                $scope.todos.unshift(data); // assign our new list of todos
                });
            }
        };

    // DELETE ==================================================================
    // delete a todo after checking it
    $scope.deleteTodo = function(id) {
        $scope.loading = true;

        Todos.delete(id)
            // if successful creation, call our get function to get all the new todos
            .success(function(data) {
                $scope.loading = false;
                $scope.todos = data; // assign our new list of todos
            });
    };

});

这是你要做的

将新字段添加到架构以存储投票:

votes: {type: Number, default: 0}
在服务器端添加一个新的处理程序,以在收到请求时递增
vote

app.get('/api/todos/:todo_id/vote', function(req, res) {
    Todo.update({_id: req.params.todo_id}, { $inc: {votes: 1} } ), function(err,doc){
    ...
    }
}
向AngularJS服务添加新函数以调用此新API处理程序:

vote: function(id) {
    return $http.get('/api/todos/' + id + '/vote');
}
连接NG单击NG重复元素以调用新的Svc函数注意:您需要在您的作用域中使用
Todos
svc来执行以下操作,否则请在作用域中创建一个包装函数,就像您所做的那样

<td>
  <button data-ng-click="Todos.vote(todo._id)" 
    class="btn.." alt="Up vote this....">Vote
  </button>
</td>

投票
然后在视图中以某种方式显示返回的ToDo模型的新“投票”字段

看看这个:你可以得到很多使用Angular、node和Mongo的好例子,看看它附带的“articles”模块


我没有尝试过这些,但它会让你知道该怎么做。此外,请注意,这里没有任何东西可以阻止用户多次向上投票。希望有帮助

你的意思是如何在数据库中“添加新名称和值并更新对象?”吗?@AsyaKamsky是的,基本上这就是我想要做的,但我也希望它将每个对象的所有点击相加。你可以使用update$inc操作符:db.coll.update({criteria:here},{$inc:{counter:1})如果计数器存在,则将其递增1;如果计数器不存在,则将其设置为1(即,当计数器不存在时,将其从隐式值0递增)。这听起来对您所描述的内容已经足够了,之后您就不需要再做任何添加了。@AsyaKamsky谢谢。我会把它放在一个函数中,然后点击调用该函数的按钮吗?我不能这么说,因为我不确定你的应用程序到底需要怎么做。当在某个对象上单击按钮时,是否会增加特定字段?有多个按钮吗?您将跟踪计数器的多项内容?它似乎没有添加要投票的点击。包装器函数是什么意思?你是说像$scope.deleteTodo这样的函数吗?是的,像deleteTodo。在上面的shld工作中,您看到了什么错误?使用上面的代码和包装器,我在控制台中没有收到任何错误$scope.updateTodo=function(id){$scope.loading=true;Todos.vote(id)//如果创建成功,调用get函数获取所有新的Todos.success(function(data){$scope.loading=false;$scope.Todos=data;//分配新的Todos列表};}@aaronsil事实上,看起来我得到了这个。GET 500(内部服务器错误)好吧,todoID为null,但它的信息太少,无法说明原因。