【问题标题】:Angular Scope in a controller控制器中的角度范围
【发布时间】:2015-01-04 21:21:05
【问题描述】:

“角度版本”:“1.3.8”,

我有以下代码 控制器像这样被传递到页面

'use strict';

/**
 * @ngdoc overview
 * @name testApp
 * @description
 * # testApp
 *
 * Main module of the application.
 */
angular
  .module('testApp', [
    'ngAnimate',
    'ngCookies',
    'ngMessages',
    'ngResource',
    'ngRoute',
    'ngSanitize',
    'ngTouch'
  ])
  .config(function($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl'
      })
      .when('/about', {
        templateUrl: 'views/about.html',
        controller: 'AboutCtrl'
      })
      .when('/test', {
        templateUrl: 'views/test.html',
        controller: 'MyCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });
  });

在 test.html 文件中

<div>
  <input ng-model="expr" type="text" placeholder="Enter an expression" />
  <h2>{{parsedValue}}</h2>
</div>

在 controller.js 文件中

'use strict';
angular.module('testApp').controller('MyCtrl', function($scope, $parse) {
  $scope.$watch('expr', function(newVal, oldVal, scope) {
    if (newVal !== oldVal) {
      // Let's set up our parseFun with the expression
      var parseFun = $parse(newVal);
      // Get the value of the parsed expression
      $scope.parsedValue = parseFun(scope);
    }
  });
});
  1. 在绑定变量 {{parsedValue}} 上方运行代码时,不会更新。
  2. 调试代码显示$scope.parsedValue 在赋值后未定义。
  3. 为什么要创建parseFun 的所有礼仪(我知道它可能是保留所有值的闭包)但它不起作用

有人可以对正在发生的事情有所了解吗......这里还有另一个类似的问题,但我相信这个问题因为它被问到的方式而存在一些问题。

【问题讨论】:

  • 解析和引用作用域上的值有效:plnkr.co/edit/Ch2WFP3XGRvCySFh4UXz?p=preview(尝试在输入框中输入x + 1。但是由于经常调用change函数,您应该循环访问几个变量$scope 上确实是 undefined 的名称。实际上,在您给定的示例中,范围内的 all 值将是未定义的,因为您没有定义任何变量,只有原始表达式(例如 @ 987654332@ 或 "test") 会起作用。这可能不是您想要的。您在输入框中输入什么值?
  • 这是您想要的行为吗:plnkr.co/edit/B1IDO8we71pB4VJnG8RH?p=preview ?
  • 谢谢。您的解释使事情变得非常清楚。我正在关注一个例子,作者并不太清楚他想要完成什么......谢谢一百万
  • 在这种情况下,我会发布 cmets 作为答案。

标签: angularjs controller angularjs-scope


【解决方案1】:

解析和引用作用域上的值:http://plnkr.co/edit/Ch2WFP3XGRvCySFh4UXz?p=preview

由于 change 函数经常被调用,代码会循环遍历几个在 $scope 上确实未定义的变量名称。实际上,在给定的示例中,范围内的所有值都是undefined,因为没有定义任何变量,只有原始表达式(例如1 + 2"test")可以工作。在链接的例子中,变量x可以在输入的表达式中使用。

但是,这可能不是您想要的。

为了能够将用户的输入复制为string,您不需要$parse 表达式。 相反,只有以下方法可以工作:

<input ng-model="expr" type="text" placeholder="Enter some text">
<h2>{{expr}}</h2>

无需控制器上的任何代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-08
    • 2016-01-16
    • 2013-06-16
    • 2015-07-20
    • 1970-01-01
    相关资源
    最近更新 更多