自定义指令未显示

时间:2015-04-07 12:57:24

标签: angularjs angularjs-directive

我的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>

我有自定义指令操作,自定义属性文本状态,文本属性就是指令中显示的文本。但是我的代码似乎不起作用(我没有错误),我是angularjs的新手,所以我想我在某个地方犯了一些菜鸟错误。

注意:我将 {{}} 更改为&lt; %%&gt; ,因此它与我的laravel刀片模板不会发生冲突

3 个答案:

答案 0 :(得分:1)

将您的字符串更改为'',并在{{}}内使用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: function(scope, element, attrs) {
   //now you have scope.text, you don't need to assign from attrs
},

$http服务应注入指令本身,而不是链接/控制器功能,如下所示:

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

此外,无需覆盖链接/控制器中的文本。您只需使用scope.text,因为它来自您的隔离范围声明。

答案 1 :(得分:1)

据我所知,除了两件事之外,其他事情都很好

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

第二个指令链接函数这里的顺序首先是范围,第二个是元素,thir属性,last是父级的控制器。如果你想在链接中使用$ http,你必须在指令中注入它而不是链接beacuse链接DI没有填写。

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

希望有所帮助:)

答案 2 :(得分:0)

尝试添加

transclude: true,

和     范围: {                     文字:&#39; =&#39;,                     州:&#39; =&#39;                 }

然后你的