angularjs 控制器访问指令范围值
angularjs controller access directive scope value
我的 html 代码中有这个带有指令的控制器。该指令具有范围值,我想从父控制器访问并显示在 html 中。希望我的示例代码能让您对我要实现的目标有一个简单的概述。
我知道这项工作使用 $rootScope.showvalue = 'pass text';在指令中有效,但不知道这是否是最佳解决方案。
app.directive('customdir', [function() {
return {
restrict: "E",
scope: {
showvalue: "="
},
link: function(scope, el, attrs) {
scope.showvalue = 'pass text';
}
};
}]);
app.controller('mycontroller', function($scope) {
alert($scope.showvalue);
});
<html>
<div ng-controller="mycontroller">
<custom-dir></custom-dir>
/* Show scope value from custom dir */
{{showvalue}}
</div>
</html>
由于您通过双向绑定绑定指令的隔离范围showvalue
属性,您可以简单地传递父范围属性作为一个属性
<customdir showvalue="showvalue"></customdir>
<p>{{showvalue}}</p>
演示 ~ http://plnkr.co/edit/W5k0hgDElklseOvjwRsS?p=preview
如果您希望 HTML 成为 <custom-dir>
,您需要将指令重命名为 'customDir'
。
- 您可以通过属性将 "showvalue" 传递给指令。
- 您可以通过指令范围的 $parent 属性 设置值。例如。范围。$parent.showvalue = 'pass text';
- 您可以使用 emit 事件将数据从子(指令)传递到父(控制器)。
- 您可以使用共享作用域直接将值设置到控制器作用域。 (不要在指令中指定范围 属性)
我的 html 代码中有这个带有指令的控制器。该指令具有范围值,我想从父控制器访问并显示在 html 中。希望我的示例代码能让您对我要实现的目标有一个简单的概述。
我知道这项工作使用 $rootScope.showvalue = 'pass text';在指令中有效,但不知道这是否是最佳解决方案。
app.directive('customdir', [function() {
return {
restrict: "E",
scope: {
showvalue: "="
},
link: function(scope, el, attrs) {
scope.showvalue = 'pass text';
}
};
}]);
app.controller('mycontroller', function($scope) {
alert($scope.showvalue);
});
<html>
<div ng-controller="mycontroller">
<custom-dir></custom-dir>
/* Show scope value from custom dir */
{{showvalue}}
</div>
</html>
由于您通过双向绑定绑定指令的隔离范围showvalue
属性,您可以简单地传递父范围属性作为一个属性
<customdir showvalue="showvalue"></customdir>
<p>{{showvalue}}</p>
演示 ~ http://plnkr.co/edit/W5k0hgDElklseOvjwRsS?p=preview
如果您希望 HTML 成为 <custom-dir>
,您需要将指令重命名为 'customDir'
。
- 您可以通过属性将 "showvalue" 传递给指令。
- 您可以通过指令范围的 $parent 属性 设置值。例如。范围。$parent.showvalue = 'pass text';
- 您可以使用 emit 事件将数据从子(指令)传递到父(控制器)。
- 您可以使用共享作用域直接将值设置到控制器作用域。 (不要在指令中指定范围 属性)