我想获取指令中作用域的变量作为 JavaScript 变量。 这是我的代码:
app.controller("Home", ["$scope", function($scope) {
...
$scope.nb_msg = data.length;
...
}]);
app.directive("myDiv", function() {
// Here, i want to get $scope.nb_msg
var nb_msg = ???;
var result = [];
// do something with nb_msg to get result
var template = "";
...
for(var i=0; i<10; i++) {
template += "<span>" + result[i] + "</span>";
}
...
return {
restrict: "E",
template: template
};
});
我该怎么办?提前致谢!
最佳答案
您可以在链接函数中访问范围:
app.directive("myDiv", function() {
return {
restrict: "E",
template: '<span ng-repeat="i in result">{{i}}</span>',
link: function(scope, element, attr) {
// Here, i want to get $scope.nb_msg
var nb_msg = scope.nb_msg;
scope.result = [];
for(var i=0; i<10; i++) {
scope.result.push(i);
}
}
};
});
关于javascript - 如何在指令中使用作用域的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24337541/