大家好,我正在开发angularjs。我在指令上遇到了问题。
我已经将scope.user.name="amin shah"
设置为链接/单击事件想要在控制器中访问这个怎么可能呢?
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";
});
}
}
});
In html:
<div ng-copntroller='yourCtrl'>
<dir user="user"></dir>
</div>
在Controller中你应该初始化user
。
或
你使用$broadcast &$emit如果父节点是控制器
在指令的链接功能中可以使用$rootScope.$emit('user_name_update',user);
在控制器中你可以监听这个事件
$scope.$on('user_name_update',function(data){
console.log(user) // its should give your updated `user` object
})
首先,你应该纠正你的链接方法,我认为你不应该在那里需要子程序。所以你也应该删除指令中的作用域绑定。您可以使用link方法到达父作用域。
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
,你应该点击元素,然后你可以从指令中看到你的名字,但在父范围
https://plnkr.co/edit/umTdfukZ22hARoLjxdL3?p =预览