【发布时间】:2026-01-08 23:15:01
【问题描述】:
我有一个指令,其模板看起来像
<!-- selectList.tpl.html -->
<div ng-if="selectList">
<p>Id: {{$id}}</p>
<p>Current list item {{currentItem}}</p>
<select ng-model="currentItem"
name="current-item"
ng-options="item as item.value group by item.group for item in selectList">
<option value="">All</option>
</select>
</div>
我正在尝试从我的指令链接函数中访问currentItem 值以创建一个监视函数,即,
app.directive('selectList', [
"$rootScope",
"$timeout",
function (
$rootScope,
$timeout
) {
"use strict";
var getList = function() {
// ...
};
return {
restrict: 'E',
templateUrl: 'selectList.tpl.html',
link: function(scope, element, attrs) {
scope.selectList = getList();
scope.currentItem = "";
console.log("scope id:", scope.$id);
scope.$watch('currentItem', function(item) {
$timeout(function() {
console.log("currentItem is", item);
angular.element("#console").append("<p>Updated item: " + item + "</p>");
});
});
}
};
}
}
但是,在链接作用域下会创建一个子作用域,用于存储对选择框值的更改。如何访问指令链接代码中的选择框更改?
我正在使用 Angular 1.1.5。
这是问题的一个问题(已更新 q 中的代码以反映问题):http://plnkr.co/edit/5eOaRE?p=preview
【问题讨论】:
-
如果你有几分钟的时间,你能不能设置一个 plunkr。
-
在不显示指令代码的情况下很难判断你有什么作用域
标签: javascript angularjs angularjs-directive angularjs-scope