在角UI路由器意见范围变量没有更新NG-点击 [英] Scope variable is not updated on ng-click in views with Angular UI Router

查看:113
本文介绍了在角UI路由器意见范围变量没有更新NG-点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下code的一个问题: Plunkr <。 / p>

当我点击该按钮时, NG-点击变化范围变量 VAR1 。但显然这个变量没有更新,看来,我所用的UI路由器创建的。它看起来像范围已复制相同的控制器内。

问题在两种情况下消失:当我使用 {{$ parent.var1}} 而不是 {{VAR1}} 从我的观点里,或者当我删除控制器:从我的国家MainCtrl声明。

谁能弄清楚发生了什么,以及如何避免这样的问题?我喜欢拆卸控制器的声明,但是角UI路由器将如何找出要使用的控制器解决方案?


解决方案

控制器和一些指示,添加元素的DOM创建自己的范围内( NG-如果 NG-开关 NG-重复 NG-视图等)。您可以使用AngularJS Batarang Chrome扩展程序来帮助调试。该值是继承的,但在孩子的范围设定值打破了继承。您可以创建自己的服务,也可以使用一个对象从父作用域继承只要你设置继承的对象的属性你会被罚款。既然你在你的控制器设置值,我用 || 来只设置的值,如果最初继承的值是不存在。 (plnkr)

  app.controller('MainCtrl',函数($范围,全局变量){
  $ scope.var1 = 1;
  $ scope.obj = $ scope.obj || {VAR1:1};
  $ scope.g =全局; //在页面访问
  $ scope.onClick =功能(){
    globals.var1 ++;
    $ scope.var1 ++;
    $ scope.obj.var1 ++;
  };
});app.service('全局',函数(){
  this.var1 = 1;
  返回此;
});

I have a problem with the following code: Plunkr.

When I click the button, the ng-click changes the variable var1 in scope. But apparently this variable is not updated in view, which I have created with UI Router. It looks like the scope have been copied inside the same controller.

The problem disappears in two situations: when I use {{$parent.var1}} instead of {{var1}}from inside my view, OR when I remove controller: 'MainCtrl' declaration from my state.

Can anyone clarify what's going on and how to avoid such problems? I like the solution with removing the controller declaration but how Angular UI Router will figure out which controller to use?

解决方案

Controllers and some directives that add elements to the dom create their own scope (ng-if, ng-switch, ng-repeat, ng-view etc.). You can use the AngularJS Batarang chrome extension to help debug them. The values are inherited, but setting the value in a child scope breaks the inheritance. You can create your own service, or you can use an object inherited from a parent scope and as long as you're setting properties on the inherited object you'd be fine. Since you're setting the value in your controller I use || to only set the value initially if an inherited value isn't there. (plnkr):

app.controller('MainCtrl', function($scope, globals) {
  $scope.var1 = 1;
  $scope.obj = $scope.obj || {var1: 1};
  $scope.g = globals; // for access in the page
  $scope.onClick = function() {
    globals.var1++;
    $scope.var1++;
    $scope.obj.var1++;
  };
});

app.service('globals', function() {
  this.var1 = 1;
  return this;
});

这篇关于在角UI路由器意见范围变量没有更新NG-点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆