【发布时间】:2015-11-26 05:21:06
【问题描述】:
我是 AngularJS 的新手,并以 webSocket 示例作为我的应用程序的基础https://github.com/AngularClass/angular-websocket/tree/master/example 应用程序应该从 webSocket 获取 JSON 数据并填充 UI。示例包含带有集合变量的工厂,并且绑定在 HTML 模板上给出结果,但是当我添加 searchStatus 变量时,我在 UI 上看不到它的自动更新(绑定)。为什么?
<div ng-app="portScanner">
<h2>Port scanner</h2>
<div ng-controller="SimplePortScannerController">
Status : {{ searchStatus }}
<form ng-submit="submit(address)">
<input type="text" ng-model="address" autofocus required>
<button type="submit">Check ports</button>
</form>
{{sum}}<br>
<div ng-repeat="message in Messages.collection | orderBy:'-timeStamp' track by $index">
<!--{{message.statusString}}-->
{{message}}
<br>
</div>
</div>
</div>
Java 脚本代码
var angularApp = angular.module("portScanner", ['ngWebSocket']);
angularApp.controller('SimplePortScannerController', function ($scope, Messages) {
$scope.sum = 0;
if ($scope.address==null){
$scope.address = "192.168.0.1";
}
$scope.Messages = Messages;
$scope.submit = function (address_message) {
if (!address_message) {
return;
};
Messages.send({
address : address_message
});
$scope.sum = $scope.sum + 1;
};
});
angularApp.factory('Messages', function ($websocket) {
var ws = $websocket('ws://localhost:8080/portscanner2/scanner');
var collection = [];
var searchStatus;
ws.onMessage(function (event) {
console.log('message: ', event);
messageJson = angular.fromJson(event.data);
if (messageJson.statusString){
searchStatus = messageJson.statusString;
}
collection.push(angular.fromJson(event.data));
});
ws.onError(function (event) {
console.log('connection Error', event);
});
ws.onClose(function (event) {
console.log('connection closed', event);
});
ws.onOpen(function () {
console.log('connection open');
});
// setTimeout(function () {
// ws.close();
// }, 300000)
return {
collection: collection,
searchStatus: searchStatus,
// status : function () {
// return ws.readyState;
// },
send : function (message) {
if (angular.isString(message)) {
ws.send(message);
} else if (angular.isObject(message)) {
ws.send(JSON.stringify(message));
}
}
};
});
谢谢!
【问题讨论】:
-
你为什么使用
SimplePortScannerController as simpleCtrl却引用$scope? -
是的,对,我会更新,只留下 SimplePortScannerController,没有 as。
标签: javascript angularjs factory