如何将警报消息与控制器绑定?

时间:2014-09-23 07:47:29

标签: angularjs

大家好我一直在尝试使用AngularJS的简单评论应用程序,如果用户在输入字段中输入空字符串,我就会停留在视图中如何获取警报消息。 / p>

HTML视图和ng-show逻辑如下

<div ng-show="alert===true" class="alert alert-warning alert-dismissible inner" role="alert">
  <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;
  </span><span class="sr-only">Close</span></button>
  <strong>Warning!</strong> You did not submit a comment.
</div>

控制器视图和$ scope逻辑如下

// pushes data back to Firebase Array
$scope.addComment = function(){

  if ($scope.newComment.text === ''){
    $scope.alert = true;         
  }
  else {
    $scope.alert = false;        
  }

  $scope.comments.$add($scope.newComment);           
  $scope.newComment = {text: '', date: ''}; 
};

问题是虽然我可以将警报消息逻辑绑定​​到HTML视图,但警报消息只显示一次,如果用户再次键入空字符串,则无法再次重复使用。

我应该使用while循环还是其他东西?任何帮助将不胜感激!

修改

感谢meriadec的反馈,我使用更简单的代码库进行了修复,如下所示。

HTML视图和ng-show逻辑如下

<div ng-show="alert===true" class="alert alert-warning inner" role="alert">
    <button type="button" class="btn" ng-click="alert=false"><span aria-hidden="true">&times;
    </span><span class="sr-only">Close</span></button>
    <strong>Warning!</strong> You did not submit a comment.
</div>

控制器视图和$ scope逻辑如下

// pushes data back to Firebase Array
$scope.addComment = function(){

  if ($scope.newComment.text === ''){
    return $scope.alert = true; 
    };   

  $scope.comments.$add($scope.newComment);           
  $scope.newComment = {text: '', date: ''}; 
};

1 个答案:

答案 0 :(得分:1)

单击alert按钮时,您可以将close属性重置为false。 BUT ,当您获得ngShow指令时,您的警报位于子范围内,因此您需要使用对象在范围之间进行正确的数据绑定。 More info here

见:

&#13;
&#13;
angular.module('demo', []);

angular.module('demo')
  .controller('DemoCtrl', function ($scope) {
  
    $scope.ui = { alert: false };
  
    $scope.addComment = function () {
      if (!$scope.myComment) {
        $scope.ui.alert = true;
      } else {
        alert('well !');
      }
    }
  
  });
&#13;
.alert {
  position: absolute;
  top: 15px;
  left: 20%;
  right: 20%;
  width: 300px;
  background: white;
  border: 1px solid black;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="demo" ng-controller="DemoCtrl">
  
  <div class="alert" ng-show="ui.alert">
    <button ng-click="ui.alert = false">close</button>
    You did not enter any comment
  </div>
  
  <form ng-submit="addComment()">
    <input type="text" ng-model="myComment">
    <input type="submit">
  </form>
  
</div>
&#13;
&#13;
&#13;