gpt4 book ai didi

javascript - 如何在 Angular 中访问从 Controller 到自定义指令的范围?

转载 作者:行者123 更新时间:2023-11-30 12:21:04 25 4
gpt4 key购买 nike

我现在正在学习 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:

http://plnkr.co/edit/AugJkl?p=preview

最佳答案

你的问题,隐晦地,在这里:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com