【问题标题】:How to watch controller asynchronous data in angular directive如何在角度指令中观看控制器异步数据
【发布时间】:2016-06-01 13:53:44
【问题描述】:

我在 Angular 1.4 中定义了一个指令,它接收一个作用域参数“b”:

(function() {
    'use strict';
    angular
        .module('m')
        .directive('mydirective', mydirective);

    /** @ngInject */
    function mydirective() {
        var directive = {
            restrict: 'E',
            templateUrl: 'app/components/mydirective/mydirective.html',
            scope: {
                b: '='
            },
            controller: MydirectiveController,
            controllerAs: 'vm',
            bindToController: true
        };
        return directive;

    /** @ngInject */
    function MydirectiveController($scope, $state) {
        var vm = this;
        //here How to watch the parameter b to refresh the directive html result?
    }

在html页面中:

<mydirective b="ctrl.b"></myupl>

在业务控制器中,b是从一个角度资源中获取的

PayService.getBusinessNumber().then(function(results){
    vm.b = {business_id: results.no};
});

在 index.route.js 中定义了路由和业务控制器,

$stateProvider
    .state('payShowInfo', {
        url: '/payShowInfo',
        templateUrl: 'app/pay_show_info.html',
        controller: 'PayShowController',
        controllerAs: 'ctrl'
    });

我的问题是,加载指令时,参数“b”未定义,如何在角度指令中观察控制器异步数据?然后用新的“b”值刷新html页面?

【问题讨论】:

  • 你已经将b绑定到你的控制器,所以你可以在你的模板中做:&lt;div&gt;{{ ctrl.b }}&lt;/div&gt;

标签: angularjs angularjs-directive angularjs-scope


【解决方案1】:

如果您将指令参数定义为“=”,则意味着您将有两种方式的数据绑定。因此,如果您更改控制器中的值,您将在视图中反映更改。

angular.module('nib', [])
    .directive('mydirective', function ($timeout) {
        return {
            restrict: 'E',
            scope: {
                b: '='
            },
            link: function ($scope, element, attrs) {

            },
            template: '<div>Test: {{b}}</div>'
        };
    })
    .controller('ctrl',function($scope){

      $scope.click = function(){ // emulating asynchronous request
        $scope.test = 'testing';
      }

    })

请参阅下面的 plnkr:

http://plnkr.co/3qs1NpU1aIhKzxyCMXjh?p=preview

【讨论】:

    猜你喜欢
    • 2013-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-29
    • 1970-01-01
    • 1970-01-01
    • 2017-10-26
    相关资源
    最近更新 更多