我想制作一个可以插入许多页面的指令。它将包含几个表单控件。当它们的值更改时,页面将做出反应。
所以我的第一步是一个包含select
框的指令。它的值是由API设置的,这很好,但当我更改所选值时,ng-model不会在作用域上创建。
所以,我从来没有见过ng模型集。我想我是在用错误的方式制造东西,但不知道它应该是什么……这意味着我不能关注它的价值,也不能因为它不存在而做出反应。
我是想做一些不可能的事情,还是只是做错了?
var app = angular.module('anapp', []);
app.controller('acontroller', function($scope) {
$scope.text = 'some text';
});
app.directive('myDirective', function() {
return {
restrict: 'E',
replace: true,
scope: {},
template: '<div><select ng-options="select as thing.name for thing in things track by thing.id" ng-model="selectedThing"></select><p>selected thing is {{selectedThing}}</p></div>',
link: function (scope) {
//imagine this comes from an API
scope.things = [{id:1, name:'one'}, {id:2, name:'two'}];
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<div ng-app="anapp" ng-controller="acontroller">
<my-directive></my-directive>
{{text}}
</div>
您的ng-options
字符串错误。我不相信有一个关键词select
。
从外观上看,你想要的是能够说"选择这个作为那个"。
那就是
//Selecting entire object
ng-options="thing as thing.name for thing in things track by thing.id"
//Selecting just id
ng-options="thing.id as thing.name for thing in things track by thing.id"
相关文档