指令中的选定项目不起作用

Selected item in directive not working

我创建了一个 select directive 并使用了该指令两次。我需要查看两者的选定项目。我该怎么办?

HTML

<div select-list="items"></div>
<div select-list="items2"></div>

控制器

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

myApp.controller('mainController', function($scope) {
    $scope.items = [
        {
            name: "1"
        },
        {
            name: "2"
        }
    ];

    $scope.items2 = [
        {
            name: "3"
        },
        {
            name:"4"
        }
    ];

    $scope.selectedValues = [];
});

Select 指令

myApp.directive("selectList", function() {
    return {
        restrict: "EACM",
        template: '<select ng-model="selectedValues" ng-options="item.name for item in data"></select>',
        scope: {
            data: '=selectList'
        }
    }
});

我需要将 "selects" 的所选项目添加到 $scope.selectedValues 中。 我尝试了 ng-change,但没有用。

需要正确创建指令:

  1. 为您的指令准备一个控制器
  2. 如果您使用的是独立作用域,请确保将 selectedValue 传递给该作用域。 例如:

指令:

myApp.directive("selectList", function(){
return{
    restrict: "EACM",
    template: '<select ng-model="selectedValues" ng-options="item.name for item in data"></select>',
    scope: {
        data: '=selectList',
        ngModel: '='
    }
    //Add link function here, crate watcher on ngModel and update it back on select dropdown selection.
})};

HTML:

<div select-list="items" ng-model="selectedValue1" ></div>
<div select-list="items2" ng-model="selectedValue2"></div>

向指令添加 link 函数并在 ngModel 上放置观察器,一旦用户更改选择,更新父 ng-model。

您的指令使用独立作用域,因此您无法从控制器访问指令或从指令访问控制器。

您必须创建一个新条目。

我给你一个 fiddle 有效的 :

https://jsfiddle.net/Lv1q2sh2/1/

// Code goes here
var myApp = angular.module('app', []);
angular.module('app')
.directive("selectList", function(){
  return {
      restrict: "EACM",
      require: 'ngModel',
      template: '<select ng-model="selected" ng-change="onSelectedValue()" ng-options="item.name for item in data"></select>',
      scope: {
          data: '=selectList'
      },
      link: function (scope, element, attr, ngModel) {
        scope.onSelectedValue = function () {
            ngModel.$setViewValue(scope.selected);
        }
      }
  }
})
.controller('mainController', function($scope) {
  $scope.items = [
      {name: "1"},
      {name: "2"}
  ];
  $scope.items2 = [
      {name:"3"},
      {name:"4"}
  ];
  $scope.selectedValues = [];
});