【发布时间】: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);
}
});
});
- 在绑定变量
{{parsedValue}}上方运行代码时,不会更新。 - 调试代码显示
$scope.parsedValue在赋值后未定义。 - 为什么要创建
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