Search code examples
javascriptangularjsjointjs

When try to call function from Controller it doesn't respond


I'm trying to call a function in my jointController from other javascript file.

var app1 = angular.module('jointApp',[]);
var createStateBox = function(label,color){

var state = new uml.State({
    position: {x: 0, y: 0},
    size: {width: 200, height: 100},
    name: "<<"+label+">>",
    events: [label+" box"],
    attrs:{rect:{fill:color},path:{"stroke-width":0}}

});
app1.controller('jointController', function($scope) {
    $scope.setDecision(state);
    alert("This is reached");
});
    paper.model.addCell(state);
}

Here is the code in jointMod.js which contains jointController

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

function JointController($scope, $http, $filter) {

    $scope.list = [];

    $scope.newMsg = 'hello';
    $scope.newDecision;

    $scope.setMsg = function(msg) {
        $scope.newMsg = msg;
    }

    $scope.sendPost = function() {
        var data = $.param({
        json: JSON.stringify({
            msg: $scope.newMsg
            })
         });

    $scope.setDecision = function(decision){
        $scope.newDecision = decision;
        alert("one two one two")
        console.log(decision);
    }

    $http({
        method: 'POST',
        url: 'http://213.65.171.121:3000/decision',
        data: $scope.newMsg,
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        transformRequest: function(obj) {
            var str = [];
            str.push(encodeURIComponent("action") + "=" + encodeURIComponent(obj));
            return str.join("&");
        }
    }).success(function(data, status, header, config) {
                $scope.list.push(status);
        }).error(function(data, status, header, config) {
                $scope.list.push(status);
        });
    };
};

I have the alert and console log in there to make sure if they can be reach but they do not responed.


Solution

  • The code you provided will not function as you may think. Atleast not if you use both together.

    Both codes introduce a new module jointApp and actually only the first one defines a controller. The $scope of that controller is NOT the same of the function in your second code.

    If you want to call a method from outside of a controller take a look at events in angular. That would be the best way to archive this. You could also use a dummy object and two-way-bind it (scope: { dummy: '=' }) and then call the method you create on that object in your directive from other code-parts.

    Take a look at this plnkr demonstrating both approaches.

    http://plnkr.co/edit/YdcB10UpXGqKAxYzXISL?p=preview