[英]Update scope variable dynamically. Angular
I have the following: 我有以下内容:
html HTML
<div class="panel panel-default" ng-controller="firstController">
<ul id="conversation">
<li ng-repeat="msg in messages">{{msg}}</li>
</ul>
</div>
js JS
var messages = [];
//Messages is updated everytime a message is sent.
var firstController = function($scope) {
$scope.messages = messages;
}
app.controller("firstController", firstController);
I have a button that updates the global javascript messages variable. 我有一个用于更新全局javascript消息变量的按钮。 I need to update the $scope messages variable everytime my button is clicked.
每次单击按钮时,我需要更新$ scope消息变量。 My controller only runs when the page first loads.
我的控制器仅在页面首次加载时运行。 How can I update $scope variables?
如何更新$ scope变量?
As it was suggested, you can use ng-click
to invoke
a function in the controller whenever the button is clicked. 如建议的那样,每当单击按钮时,都可以使用
ng-click
invoke
控制器中的函数。 You can update the messages array
within the function. 您可以在函数内更新
messages array
。
Below is a code example on how to do this. 以下是有关如何执行此操作的代码示例。 You can check this Fiddle to see it in action.
您可以检查此小提琴以查看其运作 。
<div id="appContainer" ng-app="MyApp">
<div ng-controller="MyController">
<button ng-click="updateMessages();">Click Me</button>
<div ng-repeat="msg in messages">
<label>{{msg}}</label>
</div>
</div>
</div>
var app = angular.module('MyApp', []);
app.controller('MyController', ['$scope', function($scope) {
$scope.messages = [];
$scope.updateMessages = function() {
$scope.messages.push('Date is: ' + new Date().toString());
};
}]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.