我创建了一个指令: -
return {
restrict: 'EAC',
scope: {
statesActive: '='
},
link: function (scope, element, attrs) {
var stateData = scope.statesActive.states; // Don't get data here
....
}
我的Html: -
<gt-map states-active="states"></gt-map>
控制器: -
$scope.statesList = function () {
var query = {
status: 'active'
}
StatesList.query(query).$promise.then(function (states) {
$scope.states = states;
});
};
我在这样的州获得数据: -
$scope.states = "{states:[{ 'state' : 'CA', 'color' : '#61c419']}";
如何在Controller
中获取directive
范围值?
- - - - - - - - 添加
这是我在我的指令中console.log(scope)
中看到的: -
答案 0 :(得分:1)
return {
restrict: 'EAC',
scope: {
statesActive: '='
},
link: function (scope, element, attrs) {
var stateData = angular.fromJson(attrs.statesActive).states; // Probably, your "states" model here
....
}
答案 1 :(得分:1)
对另一个答案的评论中引用了对fiddle的轻微调整,该答案现在显示了通过其范围检索指令链接函数中的状态:
link: function (scope, element, attrs) {
var stateData = $parse(scope.statesActive)();
console.log(stateData);
}
陈述:
scope: { statesActive: '=' }
您将指令的范围绑定到名为states-active
的属性,因此您只需要在指令中引用它就可以使用
scope.statesActive
这会将值作为字符串获取,您可以使用$ parse服务来获取对象的值
答案 2 :(得分:1)
$scope.states
你有错误。它必须是一个对象,而不是一个字符串。
以下代码正常工作
<强> JS 强>
angular.module('myApp', []);
angular.module('myApp').directive('gtMap',
function() {
return {
restrict: 'EAC',
scope: {
statesActive: '='
},
link: function (scope, element, attrs) {
var stateData = scope.statesActive.states;
// Don't get data here
console.log(scope.statesActive);
}
}
}
);
angular.module('myApp').controller('MyCtrl',
function($scope) {
// If states is a string got from database, use angular.fromJson(json) to parse.
// $scope.states = angular.fromJson(response);
$scope.states = {states:[{ 'state' : 'CA', 'color' : '#61c419'}]};
});
<强> HTML 强>
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<gt-map states-active="states"></gt-map>
</div>
</div>
查看此jsfiddle http://jsfiddle.net/fizerkhan/69Pq9/1/
答案 3 :(得分:0)
在你的指令中注入$ parse .... 试试这个...
angular.module('myApp').directive('gtMap', ['$parse',
function($parse) {
return {
restrict: 'EAC',
link: function (scope, element, attrs) {
var fieldGetter = $parse(attrs.statesActive);
console.log(fieldGetter)
var field = fieldGetter(scope);
//var stateData = scope.statesActive.states;
// Don't get data here
console.log(field)
}
}
}
]);
答案 4 :(得分:0)
尝试使用它来访问您的范围。
return {
...
link: function (scope, element, attrs) {
....
scope.$parent.$parent.YourVariable;
}
};
我认为您需要将HTML更改为:
<gt-map states-active="states"></gt-map>
答案 5 :(得分:0)
scope.statesActive
是一个数组,因此您需要按如下方式访问它
var stateData = scope.statesActive [0] .states;