要求未在角度中定义 [英] require is not defined in angular
问题描述
我使用的是angularjs,其中我创建了一个js文件(loginCtrl.js),并且包含一个控制器. 我已经在另一个文件(server.js)中定义了数据库连接和架构,我想将该文件包含在我的js中.
I am using angularjs where i have created a js file(loginCtrl.js) and i have inclused a controller. I have defined my db connection and schema in another file(server.js) and i want to include that file in my js.
我的loginCtrl.js看起来像:
My loginCtrl.js looks like:
test.controller('loginCtrl', function($scope, loginService){
$scope.login = function(user)
{
console.log('inside function 1');
var user = require('./server.js')
console.log('inside function');
loginService.login(user);
}
});
和我的server.js文件如下:
and my server.js files looks like:
var express = require('express');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/userregistration');
var userSchema = {
username: String,
firstname:String,
lastname: String,
email: String,
password: String
}
var User = mongoose.model('User', userSchema, 'user');
当我运行代码时,它给出如下错误:
When i run the code, it gives the error like:
ReferenceError: require is not defined
它正在打印上面定义的console.log.
It is printing the console.log defined above.
推荐答案
require()
是NodeJS函数,您的角度控制器将在没有该内置函数的浏览器中执行.如果要在客户端复制该行为,则应查看 RequireJS
require()
is a NodeJS function, your angular controller will be executed in the browser, which doesn't have that built-in function. If you want to replicate that behavior client-side, you should look at RequireJS
这篇关于要求未在角度中定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!