Angular.js:变量更改时UI不更新

时间:2015-08-25 16:32:20

标签: javascript angularjs scope

我开始了解Angular.js并为我的应用创建了此控制器:

<div ng-controller="mainController as ctrl">
    <h1 ng-bind="ctrl.generalReadStatus"><h1>
    <button ng-click="ctrl.changeReadStatus()">Change Status</button>
</div>

标记看起来像这样:

ng-click="ctrl.changeReadStatus()"

浏览器输出:

enter image description here

在html标记中,我使用NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"]; [formatter setTimeZone:timeZone]; NSDate *now = [NSDate date]; NSString *dateAsString = [formatter stringFromDate:now]; 来调用该函数并更改内容。现在,我知道值会更改,但UI(html代码)不会更新。为什么呢?

5 个答案:

答案 0 :(得分:1)

尝试更改为

self.changeReadStatus = function() {
        self.readStatus = "not readed";
    };

答案 1 :(得分:1)

问题是控制器的generalReadStatus已经过评估,并且在因变量发生变化时没有被更新。我想在你的模板中你正在做一些事情:

<p>{{ctrl.generalReadStatus}}</p>

尝试这样的事情:

<p>Today I have  {{ctrl.readStatus}} this List.</p>

答案 2 :(得分:0)

您未将此对象绑定到控制器。使用

self.changeReadStatus = function() {
       self.readStatus = "not readed";
};

代替

self.changeReadStatus = function() {
       readStatus = "not readed";
};

答案 3 :(得分:0)

您需要修改控制器上的变量

self.readStatus = "readed";
self.changeReadStatus = function() {
    self.readStatus = "not readed";
};

答案 4 :(得分:0)

我发现如果我将mark-up更改为此

<h1 ng-bind="ctrl.viewStatus(ctrl.currentViewStatus)"></h1>

<button ng-click="ctrl.changeStatus()">CHANGE VIEW STATUS</button>

和控制器

    angular.module('noteApp', []).controller('mainCtrl', [
        function() {
            var self = this;

            self.currentViewStatus = "not viewed";

            self.changeStatus = function() {
                self.currentViewStatus = "already viewed";
            }

            self.viewStatus = function(status) {
                return "The list has been " + status;
            }

        }]);

点击html

后,button会更新