我有一个带有 html 模板的自定义指令,它基本上是一个菜单选项。当用户做出选择时,它会更新指令中的 ng-model 变量。
但我希望指令内的 ng-model 变量在指令外部传递到 html 页面中。
这是代码片段:
指令:
(function() {
'use strict';
angular
.module('myModule')
.controller('myController', ['$scope', function($scope) {
$scope.sortByOptions = [
{ value:'red', displayText:'Redder' },
{ value:'blue', displayText:'Bluer' },
{ value:'gold', displayText:'Golder' },
{ value:'brown', displayText:'Browner' }
];
}]
)
.directive('myDirective', myDirective);
myDirective.$inject = [];
function myDirective() {
return {
restrict: 'A',
templateUrl: 'mydirective/sorting.html',
}
}
})();
指令的 HTML 模板:
<select ng-model="sortBy" ng-options="sortByOption.displayText for sortByOption in sortByOptions track by sortByOption.value"> </select> {{sortBy.value}}
页面的 HTML:
<div class="col-md-8 form-inline" my-directive>
</div>
<!-- need ng-model variable from my-directive passed into sortBy --> <!-- it's being called on same page. I turned a menu options into a directive to save from copying/pasting same code everywhere. when the menu option gets selected it populates a list which is the li you see below -->
<li ng-repeat="object in objects | filter: searchTool | orderBy: (sortAscending ? '' : '-') + sortBy">
<div class="plank">
<div class="plank-header">
</div>
</div>
</li>
正如您所看到的,我正在尝试将用户选择的指令中的 ng-model="sortBy"值传递到 li 中名为 sortBy 的页面的其他部分。
如果有人能举例说明他们做了什么,那就太好了。
最佳答案
我已经做了类似的事情,本质上是将指令中的变量暴露给 Controller 。您可以通过将函数从 Controller 传递到指令中来完成此操作,以便调用该函数并在 Controller 中设置一个变量。像这样的东西。
<div mydirective call-outside-function="setSortBy".....>
mycontroller function(...) {
$scope.setSortBy = function(sb) {
$scope.localSortBy = sb;
};
}
mydirective .....
link: function(scope,element,attrs) {
scope.$watch('sortBy',function(newval) {
attrs.callOutsideFunction(newval);
});
}
可能不是最优雅的解决方案,但它有效
关于javascript - 如何将变量从指令 (ngModel) 传递到指令外部的 html 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30492240/