我已经检查了所有其他帖子并相信我,这不是重复的。希望可以有人帮帮我。这是代码。
HTML 代码 - 当用户单击“报告”时,将执行 buildData。多选指令名称为 mu-ls。
<button ng-click="buildData(selected_items)">Report</button>
<div>Universe:</div>
<div><mu-ls pre-selected="member.roles" model="selected_items" options="roles"></muls></div>
指令代码 - 指令名称为 muLs。用户可以使用该指令选择多个选项。 $scope.model 给出了用户选择的 ids 数组。
angular.module('Select').directive('muLs', function () {
return {
restrict: 'E',
scope: {
model: '=',
options: '=',
pre_selected: '=preSelected'
},
template: "<div data-ng-class='{open: open}'>" +
"<button data-ng-click='open=!open;openDropdown()'>Select...</button>" +
"<ul aria-labelledby='dropdownMenu'>" +
"<li data-ng-repeat='option in options'> <a data-ng-click='setSelectedItem()'>{{option.name}}<span data-ng-class='isChecked(option.id)'></span></a></li>" +
"</ul>" +
"</div>",
controller: function ($scope) {
$scope.openDropdown = function () {
$scope.selected_items = [];
for (var i = 0; i < $scope.pre_selected.length; i++) {
$scope.selected_items.push($scope.pre_selected[i].id);
}
};
$scope.setSelectedItem = function () {
var id = this.option.id;
if (_.contains($scope.model, id)) {
$scope.model = _.without($scope.model, id);
} else {
$scope.model.push(id);
}
console.log($scope.model);
return false;
};
$scope.isChecked = function (id) {
if (_.contains($scope.model, id)) {
return 'glyphicon glyphicon-ok pull-right';
}
return false;
};
}
}
});
Controller 代码 - 这应该显示 Controller 端上面列出的所选项目的列表。目前显示未定义。
'use strict'
var Modd= angular.module('Select', []);
Modd.controller('SelectController', function ($scope, $timeout, $rootScope) {
$scope.roles = [
{ "id": 1, "name": "USA" },
{ "id": 2, "name": "France" },
{ "id": 3, "name": "Russia" }
];
$scope.member = { roles: [] };
$scope.selected_items = [];
$scope.buildData = function (selected_items) {
console.log("This is", $scope.model);
}
});
问题-我如何在 Controller 端使用这个指令值 $scope.model ???请大家推荐一下!!!
我首先尝试了 $scope.selected_items 。它仅给出一次所选项目的列表。一旦我点击报告按钮,它就会给出列表。如果我再次开始单击并取消选择列表项,它仍然会显示以前的值。不是当前的。
$scope.model 继续显示所选的最新值。
最佳答案
您将 selected_items
传递给指令,以便它将包含 Controller 中 model
的值。
$scope.buildData = function () {
console.log("This is", $scope.selected_items);
}
关于javascript - 将 $scope.model 从指令传递到 Controller (Angularjs),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33790077/