[英]AngularJS variables
我使用Yeoman和Angular-fullstack-generator构建了一个Angular应用程序。 我想为名为Book的对象提供CRUD函数,并按如下方式编写bookIndex状态:
'use strict';
angular.module('myApp')
.config(function($stateProvider) {
$stateProvider
.state('bookIndex', {
url: '/book',
referrer: 'main',
templateUrl: 'app/book/book.html',
controller: function($state) {
constructor($http, $scope, socket) {
this.$http = $http;
this.awesomeThings = [];
$http.get('/api/book').then(response => {
this.awesomeThings = response.data;
socket.syncUpdates('thing', this.awesomeThings);
});
$scope.$on('$destroy', function() {
socket.unsyncUpdates('thing');
});
}
addThing() {
if (this.newThing) {
this.$http.post('/api/book', { name: this.newThing });
this.newThing = '';
}
}
deleteThing(thing) {
this.$http.delete('/api/book/' + thing._id);
}
}
});
});
在“ constructor($ http,$ scope,socket)”(意外令牌)上停滞不前。 我知道它与不同脚本中的变量有关,但我不知道该如何处理:-(
对不起,这个新手问题!
在controller: function($state) {
您必须传递函数的主体,但是看起来您试图声明类或对象的属性。 这不是JavaScript的正确语法。
例如,它必须是:
controller: function($state) {
$scope.constructor($http, $scope);
$scope.$on('$destroy', function() {
// to do something
});
// and so on...
}
考虑对控制器指令使用最佳实践ng-strict。
ng-strict-di=true
现在,您要做的是像在不同js文件中使用控制器时一样,在app.js中初始化控制器:
angular.module('app.mainView', ['ngRoute'])
// not sure what your socket is, use the correct impl for factory, or service. If its an Angular services it should be $<name>.
.service('webSerivice', ['$http', '$q', 'webService'])
.controller('MainCtrl', ['$scope', 'webService', '$linq', MainCtrl])
要修复您的代码,请尝试对控制器进行以下更改,并注意这可能不适用于ng-strict。
您需要初始化任何套接字
angular.module('myApp')
// now you can initialize socket
.service('socket' [<dependencies>, socket])
controller: function($state, $http, $scope, socket) {
this.awesomeThings = [];
$http.get('/api/book').then(response => {
this.awesomeThings = response.data;
socket.syncUpdates('thing', this.awesomeThings);
});
// rest of your code.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.