自定义指令未显示

Custom Directive Not Showing

我的 ng-repeat 中有以下自定义指令:

<action ng-click="addToCart('event', d, type.id, $index )" text="Hey!" state="ready"></action>

action.js:

(function() {

    angular.module('vendor').directive('action', function() {
        return {
            restrict: 'E',
            scope: {
                text: '@text',
                state: '@state'
            },
            templateUrl: '/js/app/templates/action.html',
            link: ['$http', '$scope', '$element', '$attrs', function($http, $scope, $element, $attrs) {
                $scope.text = $attrs.text;
            }],
            controller: ['$http', '$scope', '$element', '$attrs', function($http, $scope, $element, $attrs) {
                $scope.text = $attrs.text;
            }],
            controllerAs: 'action'
        }
    });

}) ();

action.html:

<a ng-class="{ 'btn-set': isReady || isWorking || isComplete || hasFailed, 'btn-ready-state': isReady, 'btn-working-state': isWorking && selectedIndex == $index, 'btn-complete-state': isComplete && selectedIndex == $index, 'btn-failed-state': hasFailed }">
    <i ng-if="isReady" class="fa fa-shopping-cart"></i>
    <img ng-src="/images/loading.GIF" class="img" ng-show="isWorking && selectedIndex == $index "></span>
    <i ng-if="isComplete && selectedIndex == $index " class="fa fa-check"></i>
    <span class="text">
        <span ng-if="isReady"><% text %></span>
    </span>
</a>

我有一个自定义指令 action,带有自定义属性 textstate,文本属性只是指令中显示的文本。但是我的代码似乎不起作用(我没有收到任何错误),我是 angularjs 的新手,所以我想我在某个地方犯了一些新手错误。

注意:我将 {{ }} 更改为 <% %> 所以它不会与我的 laravel blade 模板化

更改要包裹在 '' 中的字符串,并在 action.html:

中使用 {{}}
<action ng-click="addToCart('event', d, type.id, $index )" text="'Hey!'" state="'ready'"></action>

在你的 HTML 中:

<span ng-if="isReady">{{ text }}</span>

顺便说一句,当你的作用域变量与属性同名时,你不需要提及它,你可以这样做:

scope: {
     text: '@',
     state: '@'
 },

编辑: 正如 squiroid 在他的问题中指出的那样,我认为您的 link/controller 功能有点不对劲。首先,您不需要使用 [,因为它们是用来修复注入的。你可以简单地做:

link: function(scope, element, attrs) {
   //now you have scope.text, you don't need to assign from attrs
},

$http 服务应该被注入指令本身,而不是 link/controller 函数,像这样:

.directive('action', ['$http', function($http) {
   ...
}]

此外,无需覆盖 link/controller 中的文本。您只需要使用 scope.text 因为它来自您的独立范围声明。

尝试添加

transclude: true,

和 范围: { 文字:'=', 状态:'=' }

那么你的

据我所知,除两件事外一切都很好

<span ng-if="isReady">{{ text }}</span>

第二个指令 link 这里的函数顺序首先是范围,其次是元素,他们的属性,最后是 parent.And 的控制器,如果你想在 link 中使用 $http你必须在指令本身而不是 link 中注入它,因为 link 没有被 DI 填充。

link: function($scope, $element, $attrs) {
                $scope.text = $attrs.text;
            },

希望对您有所帮助:)