【问题标题】:How to trigger an directive after a module out of my main module in angularjs如何在angularjs中我的主模块之外的模块之后触发指令
【发布时间】:2017-07-22 11:47:34
【问题描述】:

我是 AngularJS 的新手,对指令性的东西有点困惑。 在下面的代码中,我需要使用外包模块中的指令创建一个输入字段,并使用我的自定义指令关注它。
小心我不能更改外包模块...

myHtml.html

<body ng-app="main" ng-controller="myCtrl">
  <my-field></my-field>
</body>

Outsource.js

var app2 = angular.module('pain', []);
app2.directive('myField', [function() {
    return {
        scope.f = 'focus-me';
    },
    template: 'name: <input type="text" class="{{f}}"/>' +
        '<br/>' +
        'input class is: \"{{f}}\"'
}
}]);

myApp.js

var app1 = angular.module('main', ['pain']);
app1.controller('myCtrl', ['$scope', function($scope) {
    $scope.state = true;
}]);
app1.directive('focusMe', ['$timeout', '$parse', function($timeout, $parse) {
    return {
        restrict: 'C',
        link: function(scope, element) {
            scope.$watch(scope.state, function() {
                console.log('value=', scope.state);
                if (scope.state === true) {
                    $timeout(function() {
                        element[0].focus();
                    }, 20);
                }
            });
        }
    };
}]);

小提琴
fiddler

可以使用下面这段代码,但我无法更改外包代码。
它可以工作
fiddler

【问题讨论】:

    标签: javascript angularjs angularjs-directive fiddler directive


    【解决方案1】:

    您肯定必须修复 Outsource.js 中的代码才能让您工作。它有一些问题。查看我的 cmets 以获得解释:

    Outsource.js - 就在您的问题中

    var app2 = angular.module('pain', []);
    app2.directive('myField', [function() {
        return {
            /* directive scope needs to be added as a parameter to the angular directive link function before you can use it. */
            scope.f = 'focus-me';
        },
        // Your template property should be in your return object
    template: 'name: <input type="text" class="{{f}}"/>' +
            '<br/>' +
            'input class is: \"{{f}}\"'
    }
    }]);
    

    Outsource.js - 应该是什么

    var app2 = angular.module('pain', []);
    
    app2.directive('myField', function() {
      return {
        restrict: 'E',
        template: 'name: <input type="text" class="{{f}}"/>'+
              '<br/>'+
              'input class is: \"{{f}}\"',
        link: function (scope) {
              scope.f='focus-me';
        },
    
        controller: [function ($scope) {
           // Do Awesome stuff in/with $scope here
        }]
      };
    });
    

    所以告诉在 Outsource.js 中编写代码的人修复它,否则你无法实现你想要实现的目标。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-13
      • 1970-01-01
      • 2019-02-19
      • 2015-12-15
      • 1970-01-01
      • 2020-01-10
      相关资源
      最近更新 更多