Angularjs指令的指令,并访问设定范围VAR在控制器
问题描述:
嗨,我在angularjs工作。我在指令中遇到了一个问题。
我已经设置链接scope.user.name="amin shah"
/点击事件 ,并希望访问该控制器中,这怎么可能?Angularjs指令的指令,并访问设定范围VAR在控制器
var dataSourceDirective = angular.module('mydirective', []);
dataSourceDirective.directive('dir', function() {
return {
restrict: 'C',
scope: true,
link: function ($scope, element, attrs) {
element.bind('click', function() {
$scope.user.name ="amin shah";
$scope.$apply();
$('.sourceType_panel').hide();
$('#sourceType_1_panel').show();
});
}
}
});
控制器代码
$scope.demo = function() {
console.log($scope.user);`
},
答
你需要在你的指令来创建隔离范围。 给定的控制器应该是此指令的父代。
var dataSourceDirective = angular.module('mydirective', []);
dataSourceDirective.directive('dir', function() {
return {
restrict: 'C',
scope: {user:"=user"},
link: function ($scope, element, attrs) {
element.bind('click', function() {
$scope.user.name ="amin shah";
});
}
}
});
在HTML:
<div ng-copntroller='yourCtrl'>
<dir user="user"></dir>
</div>
在控制器,你应该初始化user
。
OR
您使用$broadcast & $emit如果家长控制。
指令Withing链接功能,您可以使用$rootScope.$emit('user_name_update',user);
并在控制器,你可以听此事件
$scope.$on('user_name_update',function(data){
console.log(user) // its should give your updated `user` object
})
答
,首先你应该纠正你的链接方法,我想你不应该需要孩子在那儿喝。所以你也应该在指令中删除你的作用域绑定。您可以使用链接方法访问父级范围。
app.directive('dir', function() {
return {
restrict: 'E',
link: function (scope, element, attrs) {
element.bind('click', function() {
scope.user.name ="amin shah";
scope.$apply();
});
}
}
});
,并在你的控制器,你可以定义这样的范围变量:
app.controller('MainCtrl', function($scope) {
$scope.user = {
name: ''
}
});
也应将此指令添加到HTML:
<dir>Element</dir>
<p>{{user.name}}</p>
这里工作plunkr
您应该点击元素比你可以从指令中看到你的名字,但在父范围内