无法在AngularJS中从控制器初始化对象

时间:2015-11-29 06:18:05

标签: javascript html angularjs controller initialization

fiddle看起来像这样:



var app = angular.module('testApp', []);

app.controller = angular.('testAppCtrl', function ($scope) {
    $scope.vehicle = {
        type: 'car',
        color: 'red'
    };
    $scope.vehicleDetail() = function () {
        return "Vehicle type : " + vehicle.type + ", "
        vehicle.color;
    };
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="testApp" ng-controller="testAppCtrl">

<h1>
AngularJS object ng-init powered by controller example
</h1>

Type: <input ng-model='vehicle.type' />
<br/>

Color: <input ng-model='vehicle.color'/>

Vehicle details : {{vehicleDetail()}}

</div>
&#13;
&#13;
&#13;

我试图使用函数而不是使用ng-init 来从控制器内部初始化对象。

问题

  

为什么不打印这些值?

1 个答案:

答案 0 :(得分:2)

您的代码应该如下所示,

这就是你需要定义控制器的方式,而不是app.controller = angular.('testAppCtrl', function ($scope) {

app.controller('testAppCtrl',function($scope)...

这是您需要在函数vehicleDetail中返回值的方式,在您的返回案例中,您无法访问vehicle之类的vehicle.color属性,您需要像{{{{}}那样访问它1}}因为$scope.vehicle.color在范围内。这vehicle错了,应该更正为$scope.vehicleDetail() = function () {..

$scope.vehicleDetail = function () {..

这是DEMO