模块中未解决的依赖关系

时间:2015-05-31 02:09:24

标签: angularjs angularjs-directive

我在AngularJs1.3中使用以下代码得到一个$ injector:unpr,我无法理解。

的index.html

<html lang="en" ng-app="directivesApp">
<head>
    <title>AngularJS Directive example</title>
    <script src="js/angular.min.js"></script>
    <script src="js/app.js"></script>
</head>
<body ng-controller="directiveCtrl">
    <user-info user="MD"></user-info>
    <user-info user="VP"></user-info>
</body>
</html>

app.js

angular.module('directivesApp', [])
.controller("directiveCtrl",function($scope){
    $scope.MD={ "firstName":"...","lastName":"..."};
    $scope.VP={"firstName":"...","lastName":"..."};
})
.directive("userInfo",function($scope){
    return{
    restrict:'E',
    template:'User : <b>{{user.firstName}}</b> <b>{{user.lastName}}</b>',
    scope:{user : "="}
    };
});

赞赏解决这个问题

1 个答案:

答案 0 :(得分:0)

指令中的

$scope可以通过linkcontroller方法函数访问,而不是在顶层注入。试试这个:

angular.module('directivesApp', [])
.controller("directiveCtrl",function($scope){
    $scope.MD={ "firstName":"...","lastName":"..."};
    $scope.VP={"firstName":"...","lastName":"..."};
})
.directive("userInfo",function(){
    return{
    restrict:'E',
    link: function (scope) { 
      // Scope using code here... 
    },
    template:'User : <b>{{user.firstName}}</b> <b>{{user.lastName}}</b>',
    scope:{user : "="}
    };
});

Here's a Codepen.希望这有帮助!