简体   繁体   中英

Directive never gets called angularjs

We are creating a directive to Increase and Descrease a number in a text box when user clicks on the buttons.

Here is the code of my custom directive.

var CEDirectives = angular.module('App.customnumberdirectives', [])
.directive('ngcustomNumber', ['$compile', function ($compile) {
var TEMPLATE_URL = '/customnumber/index.html';
var tem = '<div class="wrapper">' +
          '  <input type="text" data-ng-model="{{model}}" data-ng-blur="onBlurHandler()">' +
          '  <button ng-click="Increase()" style="cursor:pointer; background-color: transparent">INC</button>' +
          '  <button ng-click="Decrease()" style="cursor:pointer; background-color: transparent">DEC</button>' +
          '</div>';

// Set the default template for this directive
$templateCache.put(TEMPLATE_URL,tem);

return {
    restrict: "E",
    scope: {
        model: '@',
        onblurevent: '&'
    },
    replace: true,
    templateUrl: function (element, attrs) {
        return attrs.templateUrl || TEMPLATE_URL;
    },
    link: function (scope, element, attributes) {

        scope.onBlurHandler = function () {
            if (scope.onblurevent) {
                scope.onblurevent();
            }
        };

        scope.Increase = function () {
            alert('Inc');
        };
        scope.Decrease = function () {
            alert('Dec');
        };
    }
};
} ]);

In the html view:-

 <ngcustomNumber model="weight" onblurevent="Save"></ngcustomNumber>

(1) No error in Console.

(2) Tried putting alert on the top of the directive. No alert message comes up.

Thanks in advance!

尝试这个:

<ngcustom-number model="weight" onblurevent="Save"></ngcustom-number>

Because your compile is not done with right way.You must be sure that given scope IS ON template.For checking it you can print scope id in template.As you know every scope has it's ID,so if directive scope and template scope id is not the same,your problem is in it,and the solution is:

to compile it with right way.passing in it your directive's scope. the $compile service: $compile(template)(directiveScope);

you can console the scope and will see the fields I'm talking about

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM