标签: angularjs-directive

如何在angularjs指令中要求控制器

谁能告诉我如何在另一个angularJS指令中包含一个指令的控制器.例如,我有以下代码

var app = angular.module('shop', []).
config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/', {
        templateUrl: '/js/partials/home.html'
    })
        .when('/products', {
        controller: 'ProductsController',
        templateUrl: '/js/partials/products.html'
    })
        .when('/products/:productId', {
        controller: 'ProductController',
        templateUrl: '/js/partials/product.html'
    });
}]);

app.directive('mainCtrl', function () {
    return {
        controller: function ($scope) {}
    };
});

app.directive('addProduct', function () {
    return {
        restrict: 'C',
        require: '^mainCtrl',
        link: function (scope, lElement, attrs, mainCtrl) {
            //console.log(cartController);
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

从各方面来说,我应该能够在addProduct指令中访问控制器,但事实并非如此.有没有更好的方法呢?

javascript angularjs angularjs-directive

84
推荐指数
2
解决办法
13万
查看次数

ng-click上的确认对话框 - AngularJS

我正在尝试ng-click使用自定义angularjs指令设置确认对话框:

app.directive('ngConfirmClick', [
    function(){
        return {
            priority: 1,
            terminal: true,
            link: function (scope, element, attr) {
                var msg = attr.ngConfirmClick || "Are you sure?";
                var clickAction = attr.ngClick;
                element.bind('click',function (event) {
                    if ( window.confirm(msg) ) {
                        scope.$eval(clickAction)
                    }
                });
            }
        };
}])
Run Code Online (Sandbox Code Playgroud)

这很好但很遗憾,使用我的指令在标记内的表达式不会被评估:

<button ng-click="sayHi()" ng-confirm-click="Would you like to say hi?">Say hi to {{ name }}</button>
Run Code Online (Sandbox Code Playgroud)

(这种情况下不评估名称).这似乎是由于我的指令的终端参数.你对解决方法有什么想法吗?

测试我的代码:http: //plnkr.co/edit/EHmRpfwsgSfEFVMgRLgj?p = preview

javascript angularjs angularjs-directive angularjs-scope

84
推荐指数
5
解决办法
23万
查看次数

角度ng-if或ng-show响应慢(2秒延迟?)

我正在尝试在请求繁忙时显示或隐藏按钮上的加载指示器.我通过在加载请求或加载完成时更改$ scope.loading变量来使用angular.

 $scope.login = function(){
     $scope.loading = true;
    apiFactory.getToken()
        .success(function(data){

        })
        .error(function(error){

        })
         .finally(function(){
               $timeout(function() {
                 $scope.loading = false;
               }, 0);
         });
 };
Run Code Online (Sandbox Code Playgroud)

在前端:

<button ng-disabled="loading" class="button button-outline button-positive" type="submit">
Log in 
<span ng-if="loading" class="ion-refreshing"></span>
</button>
Run Code Online (Sandbox Code Playgroud)

这工作正常,但加载图标(离子刷新)显示约2秒,而$ scope变量立即更新.我尝试了$ scope.$ apply但这似乎不是什么错误,范围在请求后立即更新.这只是图标没有足够快速响应.

谢谢你帮我理解这个!

angularjs angularjs-directive ionic-framework

82
推荐指数
4
解决办法
3万
查看次数

如何将输入限制为仅接受数字?

我在AngularJS中使用ngChange来触发一个自定义函数,该函数将删除用户添加到输入的任何字母.

<input type="text" name="inputName" data-ng-change="numbersOnly()"/>
Run Code Online (Sandbox Code Playgroud)

问题是我需要定位触发的输入,numbersOnly()以便我可以删除输入的字母.我在Google上看了很长时间,并且无法找到任何与此有关的内容.

我能做什么?

javascript angularjs angularjs-directive

81
推荐指数
5
解决办法
16万
查看次数

如何在AngularJS中对隔离范围指令进行单元测试

在AngularJS中单元测试隔离范围的好方法是什么

JSFiddle显示单元测试

指令片段

    scope: {name: '=myGreet'},
    link: function (scope, element, attrs) {
        //show the initial state
        greet(element, scope[attrs.myGreet]);

        //listen for changes in the model
        scope.$watch(attrs.myGreet, function (name) {
            greet(element, name);
        });
    }
Run Code Online (Sandbox Code Playgroud)

我想,以确保指令监听的变化-这并不会与一个孤立的范围内工作:

    it('should watch for changes in the model', function () {
        var elm;
        //arrange
        spyOn(scope, '$watch');
        //act
        elm = compile(validHTML)(scope);
        //assert
        expect(scope.$watch.callCount).toBe(1);
        expect(scope.$watch).toHaveBeenCalledWith('name', jasmine.any(Function));
    });
Run Code Online (Sandbox Code Playgroud)

更新: 我通过检查预期观察者是否被添加到子范围来实现它,但它非常脆弱,并且可能以未记录的方式使用访问者(也可能更改,恕不另行通知!).

//this is super brittle, is there a better way!?
elm = compile(validHTML)(scope);
expect(elm.scope().$$watchers[0].exp).toBe('name');
Run Code Online (Sandbox Code Playgroud)

更新2: 正如我所说,这很脆弱!这个想法仍然有效,但在较新版本的AngularJS中,访问者已经从以下scope()变为isolateScope(): …

javascript unit-testing jasmine angularjs angularjs-directive

81
推荐指数
2
解决办法
4万
查看次数

如何使用指令定义的`replace`?

在本文档中:http://docs.angularjs.org/guide/directive,它表示有一个replace指令配置:

template - 将当前元素替换为HTML的内容.替换过程将所有属性/类从旧元素迁移到新元素.有关更多信息,请参阅下面的创建组件部分.

javascript代码

app.directive('myd1', function(){
  return {
    template: '<span>directive template1</span>',
    replace: true
  }
});

app.directive('myd2', function(){
  return {
    template: '<span>directive template2</span>',
    replace: false
  }
});
Run Code Online (Sandbox Code Playgroud)

HTML代码

<div myd1>
  original content should be replaced
</div>
<div myd2>
  original content should NOT be replaced
</div>
Run Code Online (Sandbox Code Playgroud)

但最后一页看起来像:

directive template1
directive template2
Run Code Online (Sandbox Code Playgroud)

看来这replace不起作用.我想念什么吗?

现场演示:http://plnkr.co/edit/rGIgmjO81X2UxJohL4HM?p=preview

angularjs angularjs-directive

80
推荐指数
3
解决办法
12万
查看次数

为什么不能在具有隔离范围的指令的模板中访问$ rootScope?

对于隔离范围,指令的模板似乎无法访问控制器('Ctrl')$ rootScope变量,但该变量确实出现在指令的控制器中.我理解为什么控制器('Ctrl')$ scope变量在隔离范围内不可见.

HTML:

<div ng-app="app">
    <div ng-controller="Ctrl">
        <my-template></my-template>
    </div>

    <script type="text/ng-template" id="my-template.html">
        <label ng-click="test(blah)">Click</label>
    </script>
</div>
Run Code Online (Sandbox Code Playgroud)

JavaScript的:

angular.module('app', [])
    .controller('Ctrl', function Ctrl1($scope,  $rootScope) {
        $rootScope.blah = 'Hello';
        $scope.yah = 'World'
    })
    .directive('myTemplate', function() {
        return {
            restrict: 'E',
            templateUrl: 'my-template.html',
            scope: {},
            controller: ["$scope", "$rootScope", function($scope, $rootScope) {
                console.log($rootScope.blah);
                console.log($scope.yah);,

                $scope.test = function(arg) {
                    console.log(arg);
                }
            }]
        };
    });
Run Code Online (Sandbox Code Playgroud)

的jsfiddle

访问变量时没有隔离范围 - 通过注释隔离范围行可以看出:

        // scope: {},
Run Code Online (Sandbox Code Playgroud)

javascript angularjs angularjs-directive

80
推荐指数
3
解决办法
9万
查看次数

在指令中更改鼠标悬停类

我无法弄清楚如何在嵌套指令上更改类.

这是外部ng重复

<div data-courseoverview data-ng-repeat="course in courses | orderBy:sortOrder | filter:search"
         data-ng-controller ="CourseItemController"
         data-ng-class="{ selected: isSelected }">
Run Code Online (Sandbox Code Playgroud)

下面是使用另一个指令的内部ng-repeat

<li data-ng-repeat="item in social" class="social-{{item.name}}" ng-mouseover="hoverItem(true);"
    ng-mouseout="hoverItem(false);"
    index="{{$index}}"><i class="{{item.icon}}"
    box="course-{{$index}}"></i></li>
Run Code Online (Sandbox Code Playgroud)

这是指令我正在调用悬停事件

ecourseApp.directive("courseoverview", function() { 
  return {    
    restrict : 'A',    
    replace: true, 
    /*scope: {
        index: '@'
    },*/        
    transclude: true,      
    templateUrl: "views/course-overview.html",
    link: function link(scope, element, attrs) {
        scope.switched = false;
        //hover handler
        scope.hoverItem = function(hovered){
            if (hovered) {
                element.addClass('hover');
                $('#course-0 figure').addClass('tint')
            }
            else
                element.removeClass('hover');
        };
    }  
}});
Run Code Online (Sandbox Code Playgroud)

这需要 $('#course-0 figure').addClass('tint')更改调用项.

谢谢

angularjs angularjs-directive

78
推荐指数
4
解决办法
10万
查看次数

angularjs ng-style:background-image不起作用

我正试图通过使用角度将背景图像应用于div ng-style(我之前尝试过使用相同行为的自定义指令),但它似乎不起作用.

<nav
    class="navigation-grid-container"
    data-ng-class="{ bigger: isNavActive == true }"
    data-ng-controller="NavigationCtrl"
    data-ng-mouseenter="isNavActive = true; $parent.isNavActive = true"
    data-ng-mouseleave="isNavActive = false; $parent.isNavActive = false"
    data-ng-show="$parent.navInvisible == false"
    data-ng-animate="'fade'"
    ng-cloak>

    <ul class="navigation-container unstyled clearfix">
        <li
            class="navigation-item-container"
            data-ng-repeat="(key, item) in navigation"
            data-ng-class="{ small: $parent.isNavActive, big: isActive == true }"
            data-ng-mouseenter="isActive = true; isInactive= false"
            data-ng-mouseleave="isActive = false; isInactive= true">

            <div data-ng-switch on="item.id">

                <div class="navigation-item-default" data-ng-switch-when="scandinavia">
                    <a class="navigation-item-overlay" data-ng-href="{{item.id}}">
                        <div class="navigation-item-teaser">
                            <span class="navigation-item-teaser-text" data-ng-class="{ small: isScandinavia }">{{item.teaser}}</span>
                        </div>
                    </a>
                    <span class="navigation-item-background" data-ng-style="{ 'background-image': …
Run Code Online (Sandbox Code Playgroud)

javascript angularjs angularjs-directive angularjs-ng-repeat ng-style

76
推荐指数
4
解决办法
11万
查看次数

AngularJS 1.5+组件不支持Watchers,解决方法是什么?

我一直在将自定义指令升级到新的组件架构.我读过组件不支持观察者.它是否正确?如果是这样,您如何检测对象的更改?对于一个基本的例子,我有自定义组件myBox,它有一个带有游戏绑定的子组件游戏.如果游戏组件中有更改游戏,我如何在myBox中显示警告消息?我明白有rxJS方法是否有可能纯粹在棱角分明?我的JSFiddle

JavaScript的

var app = angular.module('myApp', []);
app.controller('mainCtrl', function($scope) {

   $scope.name = "Tony Danza";

});

app.component("myBox",  {
      bindings: {},
      controller: function($element) {
        var myBox = this;
        myBox.game = 'World Of warcraft';
        //IF myBox.game changes, show alert message 'NAME CHANGE'
      },
      controllerAs: 'myBox',
      templateUrl: "/template",
      transclude: true
})
app.component("game",  {
      bindings: {game:'='},
      controller: function($element) {
        var game = this;


      },
      controllerAs: 'game',
      templateUrl: "/template2"
})
Run Code Online (Sandbox Code Playgroud)

HTML

<div ng-app="myApp" ng-controller="mainCtrl">
  <script type="text/ng-template" id="/template">
    <div style='width:40%;border:2px solid black;background-color:yellow'> …
Run Code Online (Sandbox Code Playgroud)

angularjs angularjs-directive angularjs-scope angularjs-components angularjs-1.5

76
推荐指数
2
解决办法
5万
查看次数