【问题标题】:Cant't get function in controller to trigg from angularJs directive无法在控制器中获取函数以从 angularJs 指令触发
【发布时间】:2014-09-15 23:49:34
【问题描述】:

我试图在就地编辑后在我的控制器中运行一个函数以更新我的基础数据,但它没有触发......不明白为什么。如何检查我是否在正确的范围内?我正在使用 Meanjs

作为测试,我试图在我的控制器中触发函数 testar()。

angular.module('customers').directive('editInPlace', [
function() {
    return {
        restrict: 'E',
        scope: {
            value: '='
        },
        template: '<span ng-click="edit()" ng-bind="value"></span><input ng-model="value"></input>',
        link: function (scope, element, attrs) {
            // Let's get a reference to the input element, as we'll want to reference it.
            var inputElement = angular.element(element.children()[1]);

            // This directive should have a set class so we can style it.
            element.addClass('edit-in-place');

            // Initially, we're not editing.
            scope.editing = false;

            // ng-click handler to activate edit-in-place
            scope.edit = function () {
                scope.editing = true;

                // We control display through a class on the directive itself. See the CSS.
                element.addClass('active');

                // And we must focus the element.
                // `angular.element()` provides a chainable array, like jQuery so to access a native DOM function,
                // we have to reference the first element in the array.
                inputElement[0].focus();
            };

            // When we leave the input, we're done editing.
            inputElement.prop('onblur', function () {
                scope.editing = false;
                element.removeClass('active');
                console.log("trigg");
                scope.$apply("testar()");
            });
        }
    };
}

]);

angular.module('customers').controller('CustomersController', ['$scope', '$stateParams', '$location', 'Authentication', 'Customers',
function($scope, $stateParams, $location, Authentication, Customers ) {
    $scope.authentication = Authentication;

    // Create new Customer
    $scope.create = function() {
        // Create new Customer object
        var customer = new Customers ({
            name: this.name,
            firstName:this.firstName
        });

    $scope.testar = function () {
        console.log("jojjemen från controller");
    }

}

]);

【问题讨论】:

    标签: angularjs controller directive meanjs


    【解决方案1】:

    添加到您的范围:

    scope
    {
      value: '=',
      controllerFunction: '='
    }
    

    在你调用的链接函数上:

       scope.controllerFunction();
    

    然后在 HTML 中,当您包含指令时,您需要将控制器函数作为属性传递:

    <edit-in-place value="something" controller-function="testar">
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多