模型的属性未在更改时更新

时间:2014-12-04 10:57:06

标签: javascript angularjs

我需要将状态消息绑定到变量。如果它是空的我需要隐藏div。如果它不是空的,则显示div和消息。当我在控制器中更新$scope.statusMessage.msg时,{{statusMessage.msg}}未更新。如何解决?

<div class="alert alert-info"
     ng-class="{'alert-danger': statusMessage.status == -1, 'alert-success': statusMessage.status == 1, 'alert-warning': statusMessage.status == 0}"
     role="alert"  ng-hide="(statusMessage.msg).length == 0">{{statusMessage.msg}}</div>

$scope.statusButtonAction = function(action){
    $scope.statusMessage.msg = 'Validation Error';
}

更新1

<form role="form" class="form-inline" id="status-buttons">             
    <button type="button" class="btn btn-warning btn-lg" ng-click="statusButtonAction('Validation Error')">Validation Error</button>
</form>

更新2 声明:

$scope.statusMessage = {
    msg: '',
    status: null
};

更新3

http://jsbin.com/jaquc/2/

更新4

我使用https://github.com/angular-ui/ui-router。我的配置是:

 prototypeApplication.config(function ($stateProvider, $urlRouterProvider) {
    $stateProvider.state('welcome', {
        url: '/',
        views: {
            '': {
                templateUrl: 'views/prototype/welcome.html',
                controller: 'welcomeController'
            },
            'header@welcome': {
                templateUrl: 'views/components/header.html'
            },
            'check-in@welcome': {
                templateUrl: 'views/prototype/welcome/check-in.html',
                controller: 'checkInController'

            },
            'status-buttons@welcome': {
                templateUrl: 'views/prototype/welcome/status-buttons.html',
                controller: 'checkInController'
            }

        }
    })

更新5

很奇怪,但当我从面向对象的表示切换到纯变量时,所有工作都可以:

$scope.statusMessage = '123';
$scope.statusState = null;

这是否意味着我必须使用一些技巧来使AngularJS读取对象的属性值?

3 个答案:

答案 0 :(得分:0)

确保您定义了$scope.statusMessage ie:

$scope.statusMessage = {};

在尝试在statusButtonAction函数中设置$ scope.statusMessage.msg之前。

并使用 ng-hide="!statusMessage.msg"ng-show="statusMessage.msg"  代替
ng-hide="(statusMessage.msg).length == 0"

请在此处查看工作演示http://jsbin.com/vavahi/1/edit

答案 1 :(得分:0)

我认为问题在于使用&#39; ==&#39;而不是&#39; ===&#39;。前者确实类型强制,结果有点不可靠&#39;尤其是字符串/数组...至少我使用ng-hide =&#34; myArray.length === 0&#34;作为控制和工作的方式总是应该的。

(但是,我不确定你在ng-class中尝试做什么&#34; ... == -1&#34;等等 - 至少我没有看到statusMessage。状态在您的代码中声明或使用...)

答案 2 :(得分:0)

我发现像这样编辑 ui-router 配置解决了问题

...
check-in@welcome': {
                templateUrl: 'views/prototype/welcome/check-in.html' 
/*,
                controller: 'checkInController' */ // should be removed to work!
...
相关问题