gpt4 book ai didi

javascript - 指令中的范围 true 给出了错误的结果

转载 作者:行者123 更新时间:2023-12-02 13:47:57 25 4
gpt4 key购买 nike

我在指令中将范围用作“true”。所以现在,该指令范围从父级传递到子级,但不是反向传递。我现在打印scope.name 2次。第一个在父范围中,第二个在指令中。现在我应该得到两个不同的值。但是,我得到了两者相同的范围值。请帮忙解释一下!

//module declaration 
var app = angular.module('myApp',[]);

//controller declaration
app.controller('myCtrl',function($scope){
$scope.name = "Peter";
});

//app declaration
app.directive('myStudent',function(){

return{
template: "{{name}}",
scope:true
}
controller: [function(){
$scope.name = "Roger"
}]

});
<body ng-app="myApp" ng-controller="myCtrl"> 

{{name}},

<my-student></my-student>

</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.min.js"></script>

最佳答案

您的 Controller 不符合指令。我将其放入其中并添加了 $scope 依赖项。它有效!

//module declaration 
var app = angular.module('myApp',[]);

//controller declaration
app.controller('myCtrl',function($scope){
$scope.name = "Peter";
});

//app declaration
app.directive('myStudent',function(){

return{
template: "{{name}}",
scope:true,
controller: ['$scope', function($scope) {
$scope.name = "Roger"
}]
}


});
<body ng-app="myApp" ng-controller="myCtrl"> 

{{name}},

<my-student></my-student>

</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.min.js"></script>

关于javascript - 指令中的范围 true 给出了错误的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41218662/

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