简体   繁体   English

在AngularJS的指令中使用控制器

[英]Using Controllers In Directives In AngularJS

my directive: 我的指令:

angular.module('matrixarMatrice', []).directive('mtxMatriceForm', function () {
  return {
    restrict: 'E',
    templateUrl: 'views/matrice/matrice.html',
    scope: {
      matrix: '=',
      isclicked: '=',
      selectedprice: '&'
    },
    link: function (scope, element, attrs) {
      ...
      scope.selected = function (prices) {
        scope.selected.id = prices.id;
        scope.selectedprice(prices);
      };
    }
  };
});

my controller: 我的控制器:

$scope.selectedprice = function (prices) {
  console.log(prices);
};

my html: 我的html:

<mtx-matrice-form matrix="matrix " isclicked="isclicked" selectedprice="selectedprice(prices)"></mtx-matrice-form>

In my directive when i select item i call my controller. 在我的指令中,当我选择项目时,我呼叫控制器。 I want to exploit my object prices, but the problem i have at the moment is i have an undefined in my controller. 我想利用对象价格,但是目前存在的问题是我的控制器中undefined Does anyone know the correct way of doing this? 有人知道这样做的正确方法吗?

This is the one option that you can use to include controller inside a directive! 这是可用于将控制器包含在指令中的一个选项! There are other options as well. 还有其他选择。 Hope it helps! 希望能帮助到你!

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'Lorem';
});

app.directive('directives', function() {
  return {
    restrict: 'E',
    controller: function($scope, $element){
      $scope.name = $scope.name + "impsum";
    },
    link: function(scope, el, attr) {
      scope.name = scope.name + "Ipsum";
    }
  }
})

i have found this solution: 我找到了这个解决方案:

in my directive: 在我的指令中:

...
scope.selected = function (prices) {
   scope.selected.id = prices.id;
   scope.selectedprice({prices: prices});
};
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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