我对Angularjs来说还很陌生,我试图用HTML表达式执行一个函数,但是没有用。我需要改变表情吗?
我尝试用{{fullName}}
替换{{fullName()}
,但是HTML显示中没有任何内容。
`
<div ng-app="appNaming" ng-controller="ctrlNaming">
<p>Hey guys! My name is {{fullName}}.</p>
</div>
<script>
var naming = angular.module('appNaming', []);
naming.controller('ctrlNaming', function ($scope) {
$scope.firstName = "Bob";
$scope.lastName = "Ross";
$scope.fullName = function () {
return $scope.firstName + " " + $scope.lastName;
}
});
</script>
`
我希望HTML将Bob Ross显示为全名,但输出是函数,又名`
function () {
return $scope.firstName + " " + $scope.lastName;
}
`
答案 0 :(得分:2)
您可以直接添加2个字符串,而无需使用函数。
尝试这样:
$scope.fullName = $scope.firstName + " " + $scope.lastName;
答案 1 :(得分:0)
尝试这样:
$scope.fullName = (function () {
return $scope.firstName + " " + $scope.lastName;
})()
答案 2 :(得分:0)
您应该避免在组件的控制器中使用$scope
。这使得移植到较新的角度版本变得困难。而是使用控制器的this
作为上下文。
尝试一下:
<div ng-app="appNaming" ng-controller="ctrlNaming as $ctrl">
<p>Hey guys! My name is {{$ctrl.fullName()}}.</p>
</div>
<script>
var naming = angular.module('appNaming', []);
naming.controller('ctrlNaming', function () {
var $ctrl = this;
$ctrl.firstName = "Bob";
$ctrl.lastName = "Ross";
$ctrl.fullName = function () {
return $ctrl.firstName + " " + $ctrl.lastName;
}
});
</script>