Angularjs:获取指令中另一个控制器内定义的控制器中作用域变量的值

Angularjs : get value of scope variable in a controller defined inside another controller which is inside directive

本文关键字:控制器 作用域 变量 定义 获取 另一个 Angularjs 取指令      更新时间:2023-09-26

我有一个指令,其中定义了一个控制器,并且有一个变量,比如"$scope.accesJson"。我需要从另一个控制器访问它。

代码:

angular.module('test.directives').directive("manageAccess", function() {
    return {
        restrict: "E",
        replace: true,
        templateUrl: "template/test.html",
        controller: function($scope, $element, $http) {
            $scope.accesJson = ["hi","hello"];
        }
    };
});

我有另一个控制器,

angular.module("test.controllers").controller("testController", function($scope, $http) {
    $scope.getUsers = function() {
        console.log $scope.accesJson //I need value of $scope.accesJson here.
    }
});

我该怎么做?

请帮忙,感谢

要在两个控制器之间共享资源,您可以始终使用服务或工厂。你也可以通过定义一个全局变量来实现,但这是不鼓励的。

申报工厂:

var app = angular.module('app',[])
 .factory('appSvc',[function(){
  var resources = {};
   return resources;
 }]);

请注意,您可以在工厂中声明可重用的函数。

在你的工厂申报后,记得把它正确地注入到需要它的控制器中。

app.controller('appCtrl',['appSvc',function(appSvc){
 //do something with your appSvc
 }]);

这里有一个非常简单的plnkr来展示如何使用服务/工厂来获取和设置数据。

对于深入的文档:AngularJs Service

对于在不同控制器之间共享数据,服务是一个不错的选择。这样定义一个,

angular.module("test.services").factory('DataBasket', function () {
    return {};
});

在指令中

controller: function($scope, $element, $http, DataBasket) {
        DataBasket.accessJson = ["hi", "hello"];
        $scope.accesJson = DataBasket.accessJson;
    }

来自其他控制器

angular.module("test.controllers").controller("testController", function($scope, $http, DataBasket) {
    $scope.getUsers = function() {
        console.log DataBasket.accesJson 
    }
});

您还可以在指令的链接函数中将外部$scope的属性绑定到指令,如下所示:

angular.module('foo', [])
.directive("manageAccess",
  function() {
    return {
      restrict: "E",
      replace: true,
      scope: {
        property: '='
      },
      link: function($scope) {
        $scope.property = { foo: 1 }
      }
    }
  }
)
.controller('Main',
  function($scope) {
    $scope.showAccessJsonValue = function() {
      $scope.value = $scope.accessJson
    }
  }
)

然后在您的模板中,您可以有一个调用showAccessJsonValueng-click,它将为您提供在指令中分配的值。

比如

<body ng-controller="Main">
<manage-access property="accessJson"></manage-access>
<button ng-click="showAccessJsonValue()">Show value</button>
<pre>{{value | json}}</pre>
</body>

这是一个演示Plunk。