无法使用vm绑定到范围。控制器/ html中的表示法

时间:2015-06-13 02:48:57

标签: javascript angularjs

我正在使用route参数构建更新表单以获取我需要的项目的ID。这是按预期工作的。获得更新表单的一部分是检索存储的值并将它们绑定到表单。

如果我的模型设置为这样:

<input type="text" class="form-control" id="Event_Desc" data-ng-model="eventdescription" required />

我的控制器设置如下(注意,即使用ng-resource调用REST服务)。

appItem.get({
        Id: $routeParams.Id
    }, function (result) {
        $scope.eventdescription = result.Title;
    });

它会将字段值正确设置为表单上数据库中存储的值。但是,如果我尝试使用vm。符号如下,它返回错误&#34;无法设置属性&#39; eventdescription&#39;未定义或空引用&#34;

HTML:

<input type="text" class="form-control" id="Event_Desc" data-ng-model="vm.eventdescription" required />

控制器:

appItem.get({
        Id: $routeParams.Id
    }, function (result) {
        $scope.vm.eventdescription = result.Title;
    });

为什么我无法设置vm.eventdescription的$ scope?

2 个答案:

答案 0 :(得分:1)

尝试在使用它之前实例化vm

$scope.vm = {};

appItem.get({
        Id: $routeParams.Id
    }, function (result) {
        $scope.vm.eventdescription = result.Title;
    });

答案 1 :(得分:1)

通过执行

定义控制器后,首先需要初始化vm
var vm = this;

然后将您的值设置为

vm.eventdescription = result.Title;