这是不应该做的事吗?因为我无法让它工作。
在我的 Controller 中我有
$scope.test = "someValue"
在我看来
<input ng-model="test" />
我希望发生什么
<input ng-model="someValue" />
但是,ng-model 仍然设置为“测试”。
我该如何解决?
最佳答案
这不是 ng-model
的工作方式。如果你有一个范围变量,如你的情况 test
和这个变量的值将反射(reflect)在你的 input
的 value 属性中。这意味着 someValue
将在 input
中可见。换句话说:ng-model
是一个绑定(bind)到的指令,例如使用 NgModelController
将输入、选择、文本区域(或自定义表单控件)添加到作用域上的属性。
NgModelController provides API for the ngModel directive. The controller contains services for data-binding, validation, CSS updates, and value formatting and parsing
这是一个例子:
var app = angular.module('myApp', []);
app.controller('TestController', TestController);
function TestController() {
var vm = this;
vm.myModel = "This is the model value";
vm.selectedOption = undefined;
vm.options = [{
id: '1',
name: 'Option A'
}, {
id: '2',
name: 'Option B'
}, {
id: '3',
name: 'Option C'
}];
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<body ng-app="myApp" ng-controller="TestController as vm">
<input type="text" ng-model="vm.myModel" />
<select name="mySelect" id="mySelect" ng-model="vm.selectedOption">
<option ng-repeat="option in vm.options" value="{{option.id}}">{{ option.name }}</option>
</select>
<pre ng-if="vm.selectedOption">Selected Option: {{ vm.selectedOption }}</pre>
</body>
上面的例子也展示了一些最佳实践,意味着对你的 View 使用 controllerAs
语法并明确声明你的 Controller 签名。
关于javascript - Angular - 使用范围变量设置 ng-model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33420193/