AngularJSのコントローラーに問題があり、それが2回呼び出され、配列メッセージがリセットされました...ユーザーがメッセージを書き込む単純なチャットボックスを作成したい、...AngularJSコントローラーが2回呼び出されました(ui.routerはありません)
を送っクリックして、divの中で、私はすべてのメッセージを表示するこれは私のindex.htmlです:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="theme.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="local_functions.js"></script>
<meta charset="UTF-8">
<title>Chat v0.1</title>
</head>
<body ng-app="myApp">
<h1>Welcome in Chat v0.1</h1>
<div ng-include="'myChat.html'"></div>
</body>
</html>
これはmyChat.htmlです:
<div class="chat" ng-controller="myController">
<h2>Chat altro utente</h2>
<div class="chatbox">
Messaggi inviati:
<div ng-repeat="message in listChatMessages">
<div>Messaggio: {{message.text}}</div>
</div>
</div>
<form class="messageForm" action="index.html" method="post">
<input type="text" name="msg" value="" placeholder="Write a message..." ng-model="messageText" autocofucs="autocofucs"/>
<input type="submit" name="sendMsg" value="Invia" ng-click="sendMessage()"/>
</form>
</div>
そして、これが私のlocal_functionsです.js:
var myApp = angular.module('myApp', []);
myApp.factory('chatService', function() {
var lastMessage = "";
return {
getMessage : function() {
return lastMessage;
},
setMessage : function(messages, msg) {
messages.push({
text: msg,
});
lastMessage = msg;
}
};
});
myApp.controller('myController', function($scope, chatService) {
$scope.messageText = "";
$scope.listChatMessages = [];
$scope.sendMessage = function() {
chatService.setMessage($scope.listChatMessages, $scope.messageText);
$scope.messageText = "";
};
});
アレイmessages.pushは、正しい値を持って、私はチャットボックスではなく、いくつかのミリ秒のコントローラが再びロードされ、それが$ scope.listChatMessages = []でlistChatMessagesを復元した後valueeを参照してください。
誰でも手伝ってもらえますか?アドバイスありがとう!
コードのダウンロード: zipファイル:http://wikisend.com/download/780620/AngularJSControllerTwice.zip warファイル:local_functions.jsでhttp://wikisend.com/download/635060/AngularJS-Chat.war
、私は単純な名前で私の例をsemplified;) –
変更それのmyController命名されている理由
– Hazlo8あなたが扱っていますサーバーで。それとも、あなたはクライアントに取り組んでいますか? –