只需要解释为什么这不起作用?我试图从教程点跟进教程。第一个和第二个模型工作正常。但不适合第三种模式。有人可以向我解释为什么它不起作用?提前谢谢。
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
..........
<body ng-app="mainApp" ng-controller="machineController">
<input type="text" ng-model="anyText.first" placeholder="any text here" />
<input type="text" ng-model="anyText.second" placeholder="any text here" />
<span>{{ anyText.third() }}</span>
<script>
var app = angular.module("mainApp", []);
app.controller('machineController', function($scope) {
$scope.anyText = {
first: "This is first default text",
second: "This is second default text",
third: function() {
$object = $scope.anyText;
var newtext = anyText.first + " ::: " + anyText.second;
return newtext;
}
};
});
</script>
</body>
答案 0 :(得分:3)
您必须替换此行
var newtext = anyText.first + " ::: " + anyText.second;
与
var newtext = $object.first + " ::: " + $object.second;
未定义anyText
变量
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
<body ng-app="mainApp" ng-controller="machineController">
<input type="text" ng-model="anyText.first" placeholder="any text here"/>
<input type="text" ng-model="anyText.second" placeholder="any text here"/>
<span>{{ anyText.third() }}</span>
<script>
var app = angular.module("mainApp", []);
app.controller('machineController',function($scope){
$scope.anyText = {
first: "This is first default text",
second: "This is second default text",
third: function(){
$object = $scope.anyText;
var newtext = $object.first + " ::: " + $object.second;
return newtext;
}
};
});
</script>
</body>
答案 1 :(得分:1)
anyText.first
未引用 anyText.second
和$scope
。
由于您使用$object
来引用$scope.anyText
,因此您可以尝试更改代码:
$object = $scope.anyText;
var newtext = $object.first + " ::: " + $object.second;
return newtext;
这是一个有效的工作人员https://plnkr.co/edit/1dtKDseuIqt3k3UoeEOA
答案 2 :(得分:0)
您还可以使用简单的1行替换这3行,如下所示
return $scope.anyText.first + " ::: " + $scope.anyText.second;
完整代码如下
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
..........
<body ng-app="mainApp" ng-controller="machineController">
<input type="text" ng-model="anyText.first" placeholder="any text here" />
<input type="text" ng-model="anyText.second" placeholder="any text here" />
<span>{{ anyText.third() }}</span>
<script>
var app = angular.module("mainApp", []);
app.controller('machineController', function ($scope) {
$scope.anyText = {
first: "This is first default text",
second: "This is second default text",
third: function () {
return $scope.anyText.first + " ::: " + $scope.anyText.second;
}
};
});
</script>
</body>
</html>