【问题标题】:watch is not working inside directive link in angularJswatch 在angularJs中的指令链接内不起作用
【发布时间】:2017-04-10 01:14:08
【问题描述】:

当它们是错误消息时,保存按钮应该被禁用

<user-textbox name="txtbox" error-Message="errormsg"></user-textbox>
<button  id="modalSaveButton" type="button" ng-click="save()" data-dismiss="{{ errormsg ? '' : 'modal' }}" value="Save"></button>

指令

            link(scope) {   
                        scope.errormsg = false;
                        function disableSave (n, o) {
                          const eleModalSave = 
                                angular.element(document.querySelector('#modalSaveButton'));
                                if(scope.errormsg) {
                                   eleModalSave.attr('disabled',"");
//save button should get disable if errormsg is true
                                } else {
                                   eleModalSave.removeAttr('disabled');
                                }
                        }

                        scope.$watch('errormsg',disableSave, true);
                    }

O/P:保存按钮不会被禁用,即使它们是错误的

【问题讨论】:

标签: javascript jquery html css angularjs


【解决方案1】:

所以在你写的指令标记中:

<user-textbox name="txtbox" error-Message="errormsg"></user-textbox>

您能否将标记中的属性名称更改为错误消息。 所以它看起来像:

<user-textbox name="txtbox" error-message="errormsg"></user-textbox>

Angular 会将作用域上的 this 转换为 $scope.errorMessage, 这意味着您的指令声明应如下所示:

.directive('userTextbox', function(){
  scope : {
     errorMessage :'='
  },
  link : ['$scope', function($scope){
      $scope.$watch('errorMessage', function(newVal, oldVal) {

     })]
  }
})

【讨论】:

  • 你也不应该看属性errormsg,而是看你分配给它的东西,即错误消息,它在指令范围内变成errorMessage,就像我在答案中写的一样,希望它可以理解
  • 你能确定 $scope.errorMessage 在你的范围内吗?
  • 我创建了一个 jsbin 来触发 watch 表达式,jsbin.com/qigene/edit?html,js,console,output
猜你喜欢
  • 2017-04-07
  • 2013-02-26
  • 1970-01-01
  • 1970-01-01
  • 2015-01-31
  • 1970-01-01
  • 2015-07-26
  • 2018-01-11
  • 1970-01-01
相关资源
最近更新 更多