Javascript 访问嵌套指令内的父范围变量
我在另一个指令中声明了一个指令,该指令应该使用父范围中的单个变量。这就是结构的外观: 主控制器:Javascript 访问嵌套指令内的父范围变量,javascript,angularjs,angularjs-directive,angularjs-scope,Javascript,Angularjs,Angularjs Directive,Angularjs Scope,我在另一个指令中声明了一个指令,该指令应该使用父范围中的单个变量。这就是结构的外观: 主控制器: angular.module('app') .controller('MainCtrl', function ($scope, Settings){ $scope.userName = ""; $scope.init = function(){ Settings.getUser() .then(function (res) {
angular.module('app')
.controller('MainCtrl', function ($scope, Settings){
$scope.userName = "";
$scope.init = function(){
Settings.getUser()
.then(function (res) {
$scope.userName = res.data.userName;
console.dir(res);
}).catch(function (err) {
//showError(err.data)
});
};
}
main.html
<div id="wrapper">
<!-- Navigation -->
<header></header>
<!-- /.navbar-top-links -->
<!-- /.navbar-static-side -->
<div id="page-wrapper" style="min-height: 561px;">
<div ui-view></div>
</div>
<!-- /#page-wrapper -->
</div>
我无法访问该值,我也尝试了
范围。$watch
,但仍然得到未定义的值。您需要进行3项更改
角JS对camelcase不是很好。由于某些原因,它不一致地识别/绑定它们。因此,我会使用“用户名””
传递变量时,请拆下支架。因此,不要使用{{username}}
而只使用username
您在指令中使用的变量名(用户名-请将其也更改为“用户名”)与header.html(用户名)中的变量名不匹配
希望这能解决问题
<nav class="navbar navbar-default navbar-static-top" role="navigation" style="margin-bottom: 0">
<header-notification user-name="{{userName}}"></header-notification>
</nav>
angular.module('app')
.directive('headerNotification', function (Settings, $ngBootbox) {
return {
templateUrl: 'scripts/directives/header/header-notification/header-notification.html',
restrict: 'E',
scope: {
'userName': '='
},
controller: ['$scope', function ($scope) {
console.log($scope.userName);
}],
link: function (scope, element, attrs) {
console.log(scope.userName);
}
}
});