javascript - $scopeProvider 的问题

标签 javascript angularjs angularjs-directive angularjs-service angularjs-controller

我有一个如下所示的 js 文件。

(function(){

    angular.module("MyModule",[])
    .service('testService',testService)
    .directive("testDirective",testDirective);;

    function testDirective(testService){
         var directive = {
          template: '<input type="text">',
          restrict: 'EA'
        };
        return directive;
    }

    function testService($scope){
        $scope.name = "testName";
    }

}())

当我加载页面时,我收到如下错误。

Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <- inputResourceService <- inputResourceDirective

请帮我解决这个问题。

最佳答案

$scope dependency will never be available inside service function

您应该在服务中创建一个变量,以便在所有 Angular 组件之间轻松共享

(function(){

    angular.module("MyModule",[])
    .service('testService',testService)
    .directive("testDirective",testDirective);;

    function testDirective(testService){
         var directive = {
          template: '<input type="text" ng-model="something">',
          restrict: 'EA',
          link: function(scope, element, attrs){
              scope.name = testService.name; //assigned service variable value to scope
          }
        };
        return directive;
    }

    function testService(){
        var testService = {}
        testService.name = "testName";
        return testService;
    }

}())

Working Plunkr

关于javascript - $scopeProvider 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31594007/

相关文章:

javascript - 将表单中的输入解析到下一页的最佳实践

javascript - AngularJS 重新评估有关 $location 更改的指令

javascript - 重用数组引用而不是克隆/复制 - Angular Bootstrap 导航树的多个实例

angularjs - ng-quill 文本编辑器只更新一次

javascript - 如何以 react 形式绑定(bind),即 Angular 中的 formcontrolname 和 ngmodel

javascript - 动态更改外部 Vue.js 2.x 组件的 prop 值

javascript - 如何使用下划线 throttle 进行滚动?

javascript - 在 AngularJS 中基于模型隐藏 Img

javascript - 来自 Angular JS 的 HTTP Get 请求收到空回复

javascript - AngularJS ng-重复加载状态