作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我现在正在学习 Angular,我在指导课上。我正在为自己做一些运动,但我有一个问题。
我创建了一个客户指令,我想要的是用户将在文本框中输入任何文本,然后输入的文本将显示在我的自定义指令中。
右弓还是没听懂
这是我的一些代码:
<body ng-app="myApp">
<div class="container" ng-controller="MainCtrl">
<h3>Directive</h3>
<div class="form-group">
<label>Type text: </label>
<input type="text" class="form-control" ng-model="greet_value" />
<p>Value <div flx-greet-me></div></p>
</div>
</div>
</body>
我的指令:
var myApp = angular.module('myApp',[]);
myApp.controller('MainCtrl', function(){
//some codes here
})
.directive('flxGreetMe', function() {
var html_template = '<h1>' + $scope.greet_value + '</h1>';
return {
replace: true,
restrict: 'AE',
scope: true,
template: html_template
}
});
你能帮我解决这个问题吗?我还是 Angular 的新手。
这是plnkr:
最佳答案
你的问题,隐晦地,在这里:
scope: true,
这样做的目的是将此指令范围与其他所有内容隔离开来。您可以删除它,然后执行此操作:
return {
replace: true,
restrict: 'AE',
template: html_template,
controller : function($scope) {
$scope.$watch("greet_value", function(greet_value) {
// whatever you like
});
}
}
或者您可以保留它并手动访问父作用域,如下所示:
return {
replace: true,
restrict: 'AE',
template: html_template,
scope: true,
controller : function($scope) {
$scope.$parent.$watch("greet_value", function(greet_value) {
// whatever you like
});
}
}
或者您可以像这样编写 View 使其更加灵活:
<p>Value <div flx-greet-me="greet_value"></div></p>
然后
return {
replace: true,
restrict: 'AE',
template: html_template,
scope: true,
controller : function($attrs) {
$attrs.flxGreetMe.$observe(function(arg_value) {
// whatever you like
});
}
}
(此代码均未经过测试。)
关于javascript - 如何在 Angular 中访问从 Controller 到自定义指令的范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31064300/
我是一名优秀的程序员,十分优秀!