在this website我学会了为AngularJS编写app控制器,如下所示:
Codecademy版本:
public static long getId(Context context, String number) {
long id = 0;
String displayName;
// define the columns I want the query to return
final String[] projection = new String[] {
ContactsContract.PhoneLookup.DISPLAY_NAME,
ContactsContract.PhoneLookup._ID};
// encode the phone number and build the filter URI
final Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
// query time
final Cursor cursor = context.getContentResolver().query(contactUri, projection, null, null, null);
if(cursor != null) {
if (cursor.moveToFirst()) {
displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
// HERE IS GOOD _ID!
id = cursor.getLong(cursor.getColumnIndex(ContactsContract.PhoneLookup._ID));
Log.d("_TAG_", displayName);
{
//
// v. N-1
//
Cursor cursor2 = context.getContentResolver().query(
contactUri,
projection,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{String.valueOf(id)}, null);
if(cursor2 != null) {
// Cursor valid but string below got error "android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1 : )"
displayName = cursor2.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
Log.d("_TAG_", displayName);
}
}
{
//
// v. N
//
Uri myPhoneUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(String.valueOf(id)));
Cursor phoneCursor = context.getContentResolver().query(
myPhoneUri, null, null, null, null);
for (phoneCursor.moveToFirst(); !phoneCursor.isAfterLast(); phoneCursor.moveToNext()) {
// No steps inside!
String str = phoneCursor.getString(phoneCursor
.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Nickname.NAME));
Log.d(App.LOG_TAG, "ContactUtils.getId: " + str);
}
if(phoneCursor != null) {
phoneCursor.close();
}
}
} else {
Log.d("_TAG_", "Contact Not Found @ " + number);
}
cursor.close();
}
return id;
}
但我发现它也可以这样编码:
我的版本:
app.controller
(
'PhotoController',
[
'$scope', 'photos', '$routeParams',
function($scope, photos, $routeParams)
{
photos.success
(
function(data)
{
$scope.detail = data[$routeParams.id];
}
);
}
]
);
这两个代码都有效,但有什么区别?我应该使用codecademy或我的版本吗?为什么?我的版本较短,我认为没有缺点。
答案 0 :(得分:2)
您的版本存在的问题是它无法使用缩小的代码。您必须注释您的控制器和其他模块才能使其正常工作。 您的代码将起作用,除非它没有缩小,但在缩小时,您的服务/控制器名称将被重命名并破坏您的应用程序。
有关详细信息,请参阅以下链接:https://docs.angularjs.org/guide/di
答案 1 :(得分:1)
使用您的第二个版本的代码,如果缩小,则由于角度变量必须被称为$scope, photos, $routeParams
而无法使用。
如果您执行第一个版本,它会使用任何变量名进行依赖注入。