0

有以下问题。我想做两个指令。其中一个将成为另一个的属性。像这样的东西。

<html>
<title>Directives</title>
<head lang="en">
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js" type="text/javascript"></script>
<script src="main.js"></script>
</head>
<body ng-app="app">
    <outer inner></outer>
</body>
</html>

指令源代码在这里:

var app = angular.module('app', []);

app.directive('inner', function() {
    return {
        require: "^ngModel",
        restrict: "AC",
        transclude: true,
        replace: false,
        templateUrl: /* here is a path to template it's not interesting*/,
        controller: function($scope) {
            console.log('controller...');
        },
        link: function(scope, element, attrs) {         
            console.log('link...');
        }
    };
});


app.directive('outer', function($q, $rootScope) {   
    return {        
        require: "^ngModel",
        restrict: "E",
        replace: true,
        scope: { /* isolated scope */ },
        controller: function($scope) {},
        templateUrl: /* path to template */,
        link: function (scope, elem, attrs, ctrl) {}
    }
});

问题是外部的控制器工作,但内部没有......链接和控制器功能都不起作用......无法理解出了什么问题......

有任何想法吗?

4

1 回答 1

0

它不起作用的原因是因为两个指令都被要求在同一个元素上呈现模板,并且对于应该优先考虑哪个指令不明确。

您可以通过赋予内部指令优先于外部指令的优先级来解决此问题(数字越大表示优先级越高)。

内:

app.directive('inner', function() {
   return {
       priority:2,
       restrict: "AC",
       transclude: true,
       replace: false,
       template: "<div>{{say()}}<span ng-transclude/></div>",
       controller: function($scope) {
        $scope.message = "";

        $scope.say = function() {
            return "this is message";
        };

       // $scope.say(); // this doesn't work as well
        console.log('controller...');
       },
       link: function(scope, element, attrs) {    
          // alert('hey');
          // console.log('link...');
       }
    };
 });

此外,这两个指令都不能嵌入它们的内容。一个必须是“transclude:false”,另一个必须是 transclude:true。

app.directive('outer', function($q, $rootScope) {   

    return {       
        priority:1,
        restrict: "E",
        transclude:false,
        scope: { /* isolated scope */ },
        controller: function($scope) {
        $scope.message = "";

        $scope.sayAgain = function() {
            return  "one more message";
        };

        $scope.sayAgain(); // this doesn't work as well
    },
    template: "<div>{{sayAgain()}}</div>",
    link: function (scope, elem, attrs, ctrl) {}
    }
});

这是一个工作小提琴:

JSFiddle

于 2014-05-29T05:08:24.337 回答