2013-10-23 26 views
1

我有一个这样的控制器(除去一堆东西):)如何从其他地方的脚本调用Angular控制器上的函数?

function SignupController($scope) { 

    function isDateOfBirthValid(day, month, year) { 
     // Process day, month and year and return a bool... 
     // Also update the view model with the appropriate validation message 
    } 
} 

函数isDateOfBirthValid(由控制器内部使用,但我也希望能够从外部代码调用它。

(我希望我会被告知这违反了角模式,但它确实可以节省我很多时间......)

怎么办,我需要改变控制器,这样我可以把这个外部功能?我不能仅仅将该功能移到控制器之外,因为该功能以一种重要的方式修改了视图模型的状态。

+0

究竟你 “外” 是什么意思?从另一个Angular-Something或完全独立的外部库? – Scheintod

+0

后者。具体来说,一个jQuery插件的初始化代码。 – David

回答

0

你的功能应该在顾虑之间分开。它的名字isDateOfBirthValid确实并不意味着它应该有任何副作用。

有副作用的功能部分应该移入拥有业务模型的服务中。你的控制器只需要反映模型的内容。控制器不是的型号。

This answers涉及如何更新角度外的服务。

+0

也许'validateDateOfBirth()'会是一个更好的名字。验证逻辑有副作用,如显示消息和修改CSS类是正常的。这些事情会影响视图模型,我不相信我可以在控制器之外触摸。 – David

2

比如,你可以使用角度服务

服务代码

app.service('CommonFunctions', function() { 
    this.isDateOfBirthValid = function(day, month, year) { 
     /// your code here 
    }; 

    this.function2 = function() { 
     // your code here 
    }; 
}); 

控制器代码

选项1

function SignupController($scope , CommonFunctions) { 

    $scope.isValidDOB = CommonFunctions.isDateOfBirthValid (1,2,2013); 
} 

选项2

var app = angular.module('app'); 
app.controller('SignupController', function($scope, $location, $routeParams, CommonFunctions) { 
    $scope.isValidDOB = CommonFunctions.isDateOfBirthValid (1,2,2013); 
}); 
+2

这一切都是有道理的,但它并没有回答这个问题,即如何从Angular构造(即jQuery插件)之外调用该验证方法。这个问题涉及在jQuery插件和Angular之间共享代码...如果这甚至是一个有效的问题。也许如果插件是用指令初始化的,这个问题就会消失。 – backdesk

+1

看看http://stackoverflow.com/questions/16935095/correct-way-to-integrate-jquery-plugins-in-angular-js – backdesk

相关问题