状态更改或jQuery运行所有状态时的角度重新加载服务(ui.router lib)

时间:2016-11-15 16:17:08

标签: angularjs

我有两个问题。 第一个是: 我已尝试jQuery代码和angular.service代码同样的事情。要动态清除空格中的输入字段。

$('input[type="text"]').change(function () {
    if (!this.value.replace(/\s/g, '').length) {
        this.value = "";
    }
});

angular.module('app').service('nospace', function () {
$('input[type="text"]').change(function () {
    if (!this.value.replace(/\s/g, '').length) {
        this.value = "";
    }
});

});

当我尝试全局使用jQuery时,所有角度页面都不起作用。 当我尝试使用.service工作,但当我改变状态是停止工作,直到我刷新页面。我尝试添加  $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {});并在更改状态以解决此问题时从那里调用服务,但仍然无法正常工作。 我像这样添加到控制器 angular.module('app').controller('channelAoiEditor', function (..,.., nospace) { ... some code ... }

第二个问题是正确解析url状态。 我有这个状态:

.state('edit', {
      url: '/EditCustomer/:id',
      templateUrl: 'Client/app/customers/editCustomer/editCustomer.html',
      controller: 'editCustomer'
})

当我在“编辑客户”页面并尝试直接从网址更改用户时。页面重新加载,但保留上次使用的用户而不是重新加载新用户,但URL与新用户相同。 我尝试用以下方式更改状态:

url: '/EditCustomer/{id}'
or
url: '/EditCustomer/{id:[a-zA-Z0-9/.]*}'

$rootScope.$on('$locationChangeSuccess', function (event, url, oldUrl, state, oldState) {..}我得到了更改,但是如何正确解析它以更改内容。

谢谢!

2 个答案:

答案 0 :(得分:1)

也许你需要$ scope。$ apply()和(或)$ scope。$ digest()用于重新加载页面...它发生jQuery和Javascript代码是基于转向的,以便"重绘"您需要的页面:

  

$ apply和$ digest

     

检查是否有任何绑定值发生变化的步骤实际上有一个>方法,$ scope。$ digest()。这实际上是魔术发生的地方,但我们几乎从不直接调用它,而是使用$ scope。$ apply()将为你调用> $ scope。$ digest()。

所以我将代码封装为:

$scope.$apply(function(){
  $('input[type="text"]').change(function () {
  if (!this.value.replace(/\s/g, '').length) {
    this.value = "";
  }
});

这样您就可以确保应用和更新值。

这里有一些文档http://jimhoskins.com/2012/12/17/angularjs-and-apply.html

见你:)

答案 1 :(得分:0)

我设法修复它我忘记了jQuery的一个重要区别,这是以下

private void displayNotification(String message) {
 if (message.contains("upgrade")) {
        upgradeClient(message);
    }

}

$(document).on('change', 'input[type="text"]', AddVerification) 

这是我修复它的方式

$('input[type="text"]').change(AddVerification);

和控制器:

function AddVerification() {
    if (!this.value.replace(/\s/g, '').length) {
         this.value = "";
    }
}
angular.modul('app',[....])
.service('nospace', function () {
    //jQuery trim input fields
    this.clearWhiteSpaces = function myfunction() {
        $(document).off("change", 'input[type="text"]', AddVerification)
                   .on('change', 'input[type="text"]', AddVerification);
    }
}).run(
    ['$rootScope', '$state', '$stateParams','nospace',
        function ($rootScope, $state, $stateParams,nospace) {

     $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
           nospace.clearWhiteSpaces();
     });
})

将URL正确传递给$ stateProvider.state

时仍然存在问题