[英]AngularJS: How to access directive controller's $scope properties in HTML
[英]How to access directive's controller $scope properties inside controller
我必須從控制器內部的指令控制器訪問值。
<div ng-controller="myCtrl">
<my-directive atr="xyz"></my-directive>
</div>
//這是我的指令
app.directive('myDirective',function() {
return {
restrict : 'E',
replace : false,
scope :{
atr :'@'
},
controller : function($scope) {
console.log($scope.atr); //xyz
$scope.keyPoint ="this is what i want to access inside myCtrl";
}
}
});
//這里是ctrl
app.controller('myCtrl',function($scope){
//how can I access keyPoint here
})
隔離范圍:
您應該對關鍵點使用two-way
綁定來實現此目的。
scope :{
atr :'@',
keyPoint: '='
},
這將是在您更改Directive中的值時,它會反映在Controller中 ,反之亦然
// Instantiate the app, the 'myApp' parameter must // match what is in ng-app var myApp = angular.module('myApp', []); // Create the controller, the 'ToddlerCtrl' parameter // must match an ng-controller directive myApp.directive('myDirective',function() { return { restrict : 'E', replace : false, scope :{ atr :'@', keyPoint: '=' }, controller : function($scope) { console.log($scope.atr); //xyz $scope.keyPoint ="this is what i want to access inside myCtrl"; } } }); myApp.controller('myCtrl',function($scope,$timeout){ $timeout(function(){ alert($scope.keypoint) },500) })
<!DOCTYPE html> <html ng-app="myApp"> <head> <script data-require="angular.js@1.2.7" data-semver="1.2.7" src="http://code.angularjs.org/1.2.7/angular.js"></script> <link href="style.css" rel="stylesheet" /> <script src="script.js"></script> </head> <body> <h1>Starter AngularJS app</h1> <div ng-controller="myCtrl"> <my-directive atr="xyz" key-point="keypoint"></my-directive> </div> {{keypoint}} </body> </html>
請運行此代碼段
沒有隔離范圍:
如果要在指令中獲取控制器的作用域,請不要在指令中隔離作用域。 如果隔離范圍,則無法獲得控制器的范圍。
// Instantiate the app, the 'myApp' parameter must // match what is in ng-app var myApp = angular.module('myApp', []); // Create the controller, the 'ToddlerCtrl' parameter // must match an ng-controller directive myApp.directive('myDirective',function() { return { restrict : 'E', replace : false, controller : function($scope) { console.log($scope.atr); //xyz $scope.keyPoint ="this is what i want to access inside myCtrl"; } } }); myApp.controller('myCtrl',function($scope,$timeout){ $scope.atr="xyz" $timeout(function(){ alert($scope.keyPoint) $scope.$apply(); },500) })
<script data-require="angular.js@1.2.7" data-semver="1.2.7" src="http://code.angularjs.org/1.2.7/angular.js"></script> <link href="style.css" rel="stylesheet" /> <script src="script.js"></script> <body ng-app="myApp"> <h1>Starter AngularJS app</h1> <div ng-controller="myCtrl"> <my-directive ></my-directive> <h1>{{keyPoint}}</h1> </div> </body>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.