[英]AngularJs accessing scope outside from another function in javascript
我想借助AngularJS更改html中變量的值。 為此,我知道可以調用onclick函數,這將使我們能夠更改值:javascript代碼:
var app = angular.module('graphApp', []);
app.controller('graphAppCtrl', function($scope) {
$scope.count = 0;
$scope.myFunction = function() {
$scope.names= {0:{'Name':'John','Country':'albania'}};
$scope.count++;
keyword_type = 1
check();
}
});
現在,我想在執行一些計算后從函數外部更改變量名稱的值。 這樣做的程序是什么?
HTML:
<div id="search-container" ng-app="graphApp" ng-controller="graphAppCtrl">
<tabs id="mainTabs">
<pane title="Name search">
<p>Name: <input type="text" ng-model="name"></p>
<button ng-click="myFunction()">Search</button>
<table>
<tr>
<td>Index</td>
<td>Name</td>
<td>ID</td>
</tr>
<tr ng-repeat="x in names">
<td>{{ x.Name }}</td>
<td>{{ x.Country }}</td>
</tr>
</table>
<p ng-bind="check"></p>
</pane>
從此函數獲取價值:
function WebSocketTest(keyword_or_query,keywordtype) {
var object_of_each_pair = [];
if ("WebSocket" in window) {
//messageContainer.innerHTML = "WebSocket is supported by your Browser!";
var ws = new WebSocket("ws://localhost:8888/websocket");
ws.onopen = function() {
var message=[]
message = keyword_or_query + 'XXXX' + keywordtype
ws.send(message);
};
ws.onmessage = function (evt) {
var received_msg = evt.data;
node_id = received_msg
}
( 小提琴 )
角度環境:
app.controller('graphAppCtrl', function($scope) {
$scope.some_info = 'foo';
});
這是從外部Angular環境中檢索scope
:
// in your case
var where_you_put_ng_app = document.getElementById("search-container");
var scope = angular.element(where_you_put_ng_app).scope();
// from here you can modify your $scope variables
scope.some_info = '.....';
如果您的$ scope.myFunction()和WebSocketTest()都在同一控制器中,那么在獲得響應后,您可以將值分配給$ scope.names
如果兩者都在不同的控制器中,則在WebSocketTest()中獲取值后,可以使用$ rootScope。$ broadcast這樣
假設您擁有自己的價值
currentVariable//just name of variable
然后
$rootScope.$broadcast("broadCastonmessage",currentVariable)
//from here we will broadcast once we got the value
現在在您的控制器中
$rootScope.$on('broadCastonmessage',function($event,Value){
//this part will be executed whenever broadcast is done
//now value can be assigned to scope variable
$scope.names =value
})
這是一個簡單的示例,顯示了如何使用廣播將更改后的變量分配給其他范圍內的其他變量,希望對您有幫助
如果我理解正確,則想從javascript中的angularjs外部更改控制器的變量值。
如果是這樣,您應該獲取當前作用域並$apply
進行更改,如下所示:
var scope = angular.element($("any class name from your DOM")).scope();
//in order to update the new values to the controller , '$apply'
scope.$apply(function () {
//here you can call and change any variable from your controller
scope.names= {0:{'Name':'xxxx','Country':'xxxx'}};
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.