一尘不染

将Angular作用域变量传递给Javascript

angularjs

我有一个Angular作用域变量streetName。

<script type="text/javascript">
    angular.module('addApp').controller('add', ['$scope',function($scope) {
           $scope.streetName = "Bonita Ln";
    }]);
</script>

如何在此控制器(添加)作用域下定义的javascript中访问streetName。请帮忙。

<div ng-app="addApp" ng-controller="add">
StreetName: {{streetName}}

<script type="text/javascript">
//here i need to access the value of streetName...
</script>

</div>

阅读 263

收藏
2020-07-04

共1个答案

一尘不染

这种方法很长,但是有效:

    angular.element(document.querySelector('[ng-controller="add"]')).scope().streetName

更具可读性:

    var dom_el = document.querySelector('[ng-controller="add"]');
    var ng_el = angular.element(dom_el);
    var ng_el_scope = ng_el.scope();
    var street_name = ng_el_scope.streetName;

如果使用jQuery,它会更短:

    var street_name = $('[ng-controller="add"]').scope().streetName;

链接到jsfiddle演示

2020-07-04